<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Fang Jin on Medium]]></title>
        <description><![CDATA[Stories by Fang Jin on Medium]]></description>
        <link>https://medium.com/@windmaomao?source=rss-f6ef5f80c131------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rTc_kY01NelTAPqho9bcPw.jpeg</url>
            <title>Stories by Fang Jin on Medium</title>
            <link>https://medium.com/@windmaomao?source=rss-f6ef5f80c131------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:44:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@windmaomao/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OAuth explained in simple words, part I]]></title>
            <link>https://windmaomao.medium.com/oauth-explained-in-simple-words-part-i-2423dad857fc?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/2423dad857fc</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 19:08:54 GMT</pubDate>
            <atom:updated>2025-12-07T19:08:54.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSQ2WWGnlQfVeCpMxIuGWQ.png" /></figure><p>I have to work with Oauth lately, and interestingly I found it’s rare to find a person who carries the same dictionary as others when it comes to OAuth. So in this article I’d like to explain a bit what is OAuth in plain language so that at least we know the basic what it is doing for us.</p><p>There are three actors in the OAuth process:</p><h4>Resource owner (You)</h4><p>The resource owner is the easiest thing to start with. It is you. You own something, you want to access something. It’s you who need to login through that username/password screen. In this scenario, you are doing it for a third party who would like to manage your data.</p><h4>Third party (App)</h4><p>The third party is the app you are using, we normally refer it as the client application. In old days, we just tell it who we are directly through login, but in this case, the third party says that he doesn’t want to be responsible for the job. So he redirects you to an Oauth server to help. This step can be transparent to some user, because all they see is a popup window. But to some uer, it can be also confusing because you land on Google/Microsoft website out of nowhere.</p><h4>OAuth server (Google/Microsoft)</h4><p>Since everyone trusts Google/Microsoft and has an account with them already, we naturally use them as OAuth provider. And most likely you have already logged yourself in for that day, so by the time the third party redirects you to OAuth, the so called “login window” turns out to be actually a popup window to ask you authorize to use your user information, such as your name, profile picture and etc.</p><p>One of the most confusing part of OAuth process is: the authentication is assumed to be done by the OAuth provider (Google/Microsoft), therefore OAuth isn’t referred as authentication from the perspective of the third party (app). Instead, only the authorization is performed. But <strong>in public conversation, we all mixed this process with the authentication because we tend to stick to our old language using the word login. </strong>And the user have to login because they haven’t done that.</p><h4>Summary</h4><p>Let me summarize the OAuth in plain language. From the user experience, a user authorizes the usage of certain resources to a third party via OAuth server. <em>And the user has to login if he happens not to be logged in at that time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2423dad857fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Module federation for micro-frontend setup — part C]]></title>
            <link>https://windmaomao.medium.com/module-federation-for-micro-frontend-setup-part-c-f856fa54900e?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/f856fa54900e</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[module-federation]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 17:45:03 GMT</pubDate>
            <atom:updated>2025-10-18T17:45:03.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>Module federation for micro-frontend setup — part C</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDKaUb82qicd2--Njk-Dag.png" /></figure><p>In <a href="https://medium.com/@windmaomao/module-federation-for-micro-frontend-setup-part-b-853e24e54945">part B</a> of micro-frontend setup, we went through how to prefetch a remote page A after we land on a remote page B. So that when we are ready to display page A, it will be lightening fast.</p><p>Using the module federation provided by webpack, everything can be done using the plugin settings:</p><pre>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &quot;pageb&quot;,<br>      filename: &quot;remoteEntry.js&quot;,<br>      exposes: {<br>        &quot;./PageB&quot;: &quot;./src/PageB&quot;,<br>      },<br>      shared: { react: { singleton: true }, &quot;react-dom&quot;: { singleton: true } },<br>      remotes: {<br>        pagea: &quot;pagea@/http://localhost:3002/remoteEntry.js&quot;,<br>      },<br>    }),</pre><p>For a remote or a shell, as long as we expose via exposes or consume via remotes, we can make any page to prefetch other pages while serving as one of the remote page. The above is the webpack config for the page B.</p><p>We still have a hanging fruit task to do: that is to display the prefetched page dynamically. On day one, we were taking the shell to fulfill that job for granted:</p><pre>// Shell app<br><br>const PageA = React.lazy(() =&gt; import(&quot;pagea/App&quot;))<br>const PageB = React.lazy(() =&gt; import(&quot;pageb/PageB&quot;))<br><br>const App = () =&gt; {<br>  const [displayed, setDisplayed] = useState(false)<br><br>  const onPrefetch = () =&gt; {<br>    import(&quot;pagea/App&quot;)<br>  }<br><br>  const onDisplay = () =&gt; {<br>    setDisplayed(true)<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;h1&gt;Shell&lt;/h1&gt;<br>        &lt;button onClick={onPrefetch}&gt;<br>          prefetch page A<br>        &lt;/button&gt;<br>        &lt;button onClick={onDisplay}&gt;display page A&lt;/button&gt;<br>      &lt;/div&gt;<br>      {displayed &amp;&amp; (<br>        &lt;Suspense fallback={&quot;loading page a...&quot;}&gt;<br>          &lt;PageA /&gt;<br>        &lt;/Suspense&gt;<br>      )}<br>      &lt;Suspense fallback={&quot;loading page b...&quot;}&gt;<br>        &lt;PageB /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>In our example, we have page B loaded on the shell load. And we press a button to load and display page A. And in previous story, we extended it so that the page B can prefetch page A:</p><pre>const PageB = () =&gt; {<br>  const onPrefetch = () =&gt; {<br>    import(&quot;pagea/App&quot;)<br>  }<br>  const onDisplay = () =&gt; {<br>     // WHAT SHOULD WE DO HERE!<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Page B - v1&lt;/h1&gt;<br>      &lt;button onClick={onPrefetch}&gt;prefetch page A&lt;/button&gt;<br>      &lt;button onClick={onDisplay}&gt;display page A&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default PageB</pre><p>If we also want to display page A at the page B level, what should we do? Imaging we have a button similar to the shell but this time installed in the page B.</p><p>We actually have two choices.</p><h4><strong>Do it inline</strong></h4><p>We have the whole module content loaded for the page A, so why not we just render it:</p><pre>export default function PageB() {<br>  const [PageA, setPageA] = useState(null);<br><br>  useEffect(() =&gt; {<br>    // load PageA on mount<br>    import(&#39;pageA/App&#39;).then(mod =&gt; {<br>      setPageA(() =&gt; mod.default);<br>    });<br>  }, []);</pre><p>This does work! All in all, this is still React code. To make the display smooth, we could hide page B which is itself and then display page A once fetched.</p><p>As you can see, this works but this isn’t ideal. Because not only we have to fake the page change, but we defeat the purpose of the routing. In your application, you most likely have a router implemented in the shell. So it’s better to let the shell handle the routing. This leads to our second option.</p><h4>Notify the shell</h4><p>Why not we continue to let the shell do the right thing while exposing the routing change api.</p><pre>const App = () =&gt; {<br>  const [displayed, setDisplayed] = useState(false)<br><br>  const onPrefetch = () =&gt; {<br>    import(&quot;pagea/App&quot;)<br>  }<br><br>  const onDisplay = () =&gt; {<br>    setDisplayed(true)<br>  }<br><br>  useEffect(() =&gt; {<br>    window.addEventListener(&quot;display&quot;, ({ detail }) =&gt; {<br>      onDisplay()<br>    })<br>  }, []) </pre><p>Let us listen to a custom event display , the name is arbitrary, the whole point is that as long as someone fires that event in the same Javascript app, the shell can do something accordingly. In our case, it’ll display page A.</p><p>The rest is easy. We can go back to the page B and ask it to send the event whenever the display is ready:</p><pre>const PageB = () =&gt; {<br>  const onPrefetch = () =&gt; {<br>    import(&quot;pagea/App&quot;)<br>  }<br><br>  const onDisplay = () =&gt; {<br>    window.dispatchEvent(new CustomEvent(&quot;display&quot;, { detail: &#39;anything&#39; }))<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Page B - v1&lt;/h1&gt;<br>      &lt;button onClick={onPrefetch}&gt;prefetch page A&lt;/button&gt;<br>      &lt;button onClick={onDisplay}&gt;display page A&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>} </pre><p>Wow. The best part of this approach is that a custom event could carry any data, ex. you can make a generic navigate function by sending the url /pageA. Let us take a look what the UI would look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6beEeH9pLdHbxY4y6mdxQ.png" /></figure><p>The workflow is almost identical as the part B story except the button to display A is installed at the page B. Isn’t this cool?</p><p>By now, any remote page can prefetch another remote page and display it.</p><h4>Bonus</h4><p>We don’t actually have a router other than a displayed flag. In a real application with react-router-dom, can the case become more complicated?</p><p>No really. All the code are written in React, though there’re couple of repos, but webpack will stitch them together in the runtime. This means, the above approach is still valid.</p><p>You might have the question that can we ask the page B to navigate to page A using the native react router navigate ? This is a tricky and interesting question. The short answer is No.</p><p>You can’t install another react-router-dom in the page B code, because if you do, both router from the page B and the shell wouldn’t talk to the same context, this means /pageA wouldn’t mean the right route under the page B router. Unless you manage to share the router from the shell to the page B, that could be different story, I’ll leave that to the reader to explorer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f856fa54900e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Module federation for micro-frontend setup — part B]]></title>
            <link>https://windmaomao.medium.com/module-federation-for-micro-frontend-setup-part-b-853e24e54945?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/853e24e54945</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[module-federation]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 19:17:32 GMT</pubDate>
            <atom:updated>2025-10-11T19:17:32.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>Module federation for micro-frontend setup — part B</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDKaUb82qicd2--Njk-Dag.png" /></figure><p>In <a href="https://medium.com/@windmaomao/module-federation-for-micro-frontend-setup-part-a-bf47358c8fb2">part A</a> of micro-frontend setup, we went through how to use module federation to load a page content as a web resource in the runtime. We call import with the module name to load the module :</p><pre>import(&#39;pageA/App`);</pre><p>Now imaging we have another page, say the page B. What if we want to prefetch this page A from the page B?</p><p>Let’s start with setting up the new repo for the page B in its webpack config:</p><pre>// Page B repo<br>// webpack.config.js<br><br>module.exports = {<br>  ...<br>  devServer: {<br>    static: path.join(__dirname, &quot;dist&quot;),<br>    port: 3003,<br>  },<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &quot;pageb&quot;,<br>      filename: &quot;remoteEntry.js&quot;,<br>      exposes: {<br>        &quot;./PageB&quot;: &quot;./src/PageB&quot;,<br>      },<br>      shared: { react: { singleton: true }, &quot;react-dom&quot;: { singleton: true } },<br>    }),<br>  ...<br>};</pre><p>This config is exactly same as the page A setup with only the name changes:</p><ul><li>the remote is named pageb</li><li>the module is named PageB</li><li>the source file is named ./src/PageB</li><li>the port is set at 3003</li></ul><p>Now let’s code the component ./src/PageB inside the page B repo:</p><pre>const PageB = () =&gt; {<br>  const onPrefetch = () =&gt; {<br>    import(&#39;pagea/App&#39;)<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Page B - v1&lt;/h1&gt;<br>      &lt;button onClick={onPrefetch}&gt;prefetch page A&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Interestingly when I try to run the above code, an error is thrown at the command line console:</p><pre>ERROR in ./src/PageB.js 4:4-23<br>Module not found: Error: Can&#39;t resolve &#39;pagea/App&#39; in &#39;/pageB/src&#39;<br>resolve &#39;pagea/App&#39; in &#39;/pageB/src&#39;<br>  Parsed request is a module<br>  using description file: /pageB/package.json (relative path: ./src)<br>    Field &#39;browser&#39; doesn&#39;t contain a valid alias configuration<br>    resolve as module</pre><p>This build-time error complains that the module pagea/App can’t be found. Why a build-time error instead of runtime Javascript error?</p><p>Think about it, when webpack runs the import, it goes through the config file so it knows how many remote/module has been registered so when it sees a new key such as pagea/App that is not registered, it fails the build.</p><p>To fix this error, we can take a look at the the webpack config for the shell repo, since it can find the page A module with no issues:</p><pre>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &quot;shell&quot;,<br>      remotes: {<br>        pagea: &quot;pagea@http://localhost:3002/remoteEntry.js&quot;,<br>        pageb: &quot;pageb@http://localhost:3003/remoteEntry.js&quot;,<br>      },</pre><p>This is how the shell app gets to know we have a remote called pagea. In order to let the page B knows that, we can add the same line to the page B webpack config.</p><blockquote>Depending on if you are using typescript, you might also need to fix the module name in tsconfig file so that your editor doesn’t complain the import either.</blockquote><p>Let’s try that:</p><pre>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &quot;pageb&quot;,<br>      filename: &quot;remoteEntry.js&quot;,<br>      exposes: {<br>        &quot;./PageB&quot;: &quot;./src/PageB&quot;,<br>      },<br>      shared: { react: { singleton: true }, &quot;react-dom&quot;: { singleton: true } },<br>      remotes: {<br>        pagea: &quot;pagea@/http://localhost:3002/remoteEntry.js&quot;,<br>      },<br>    }),</pre><p>With this change, the shell app can be built and loaded successfully. It should look like in the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFz-6Fz9OVJcmF2AJYDFIg.png" /></figure><p>Our idea is to load the shell and the page B, and then prefetch the page A from that page. We will ignore the prefetch page A button from the shell level, that was from the previous article. Instead, focus on the new prefetch page A button at the page B level (inside the blue section).</p><p>On the initial load, only page B module is loaded and displayed. Now if we click the button to prefetch page A, you will see the page A (./src_App_js.js) loaded and we can confirm that in the network tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zx22YDpa7gJQBgKbKfM_bQ.png" /></figure><p>Now if we click the display page A button at the shell level, we can see the page A displayed without making additional network call.</p><p>That’s it.</p><h4>Bonus</h4><p>This exercise simulates the routing using a shell and two pages A/B. The point is that we want to know how to prefetch a page and display it at different timings. And we also want to make sure no matter what each page is only loaded once.</p><p>We manage to do this by setup webpack configs in three repos, the shell, the page A and the page B. On the initial page load, two remotes are called and registered, it loads both registry file, one from the page A and one from the page B. But no real module content of either page is loaded at that initial point.</p><p>Next, the shell goes loading the page B. The page B content gets fetched from the module content through a new http call, and it’s displayed afterwards.</p><p>If you open the browser, you can see a global variable window.pageB gets created. This is how webpack inits the remote and gets the module content.</p><pre>window.pageb = {<br>  init: () =&gt; {},<br>  get: (module) =&gt; {}<br>}</pre><p>Next, we click the prefetch page A button. The page A is then loaded by fetching the module content through a new http call. But we don’t display the page A yet. Similarly, there’s a new global variable window.pagea gets created:</p><pre>window.pagea = {<br>  init: () =&gt; {},<br>  get: (module) =&gt; {}<br>}</pre><p>Now we can answer the question why both of the shell and the page B can display the page A from now on. Since they are global variables, anyone who knows the syntax of the function can call to display the page content. Moreover, the content will not be loaded again if fetched already.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=853e24e54945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Module federation for micro-frontend setup — part A]]></title>
            <link>https://windmaomao.medium.com/module-federation-for-micro-frontend-setup-part-a-bf47358c8fb2?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf47358c8fb2</guid>
            <category><![CDATA[module-federation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 17:52:01 GMT</pubDate>
            <atom:updated>2025-10-06T17:52:01.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>Module federation for micro-frontend setup — part A</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cma_Rp4ANuyg4Exk4zu5nA.png" /></figure><p>Micro-frontend setup has been a hot topic for a while, to be honest, every company does it differently. This requirement isn’t new, as far as I remember, the need can be dated back ten or twenty years ago. The basic requirement is that we have couple of pages (or components) to display dynamically, but the code associated with them needs to be fetched dynamically on the run.</p><blockquote>Don’t be confused about the micro-frontend design vs individule pages. Micro-frontend is about sharing something on the parent level, for instance, header, footer or any other important utilities for the domain. Basically, there’s something as a parent. <strong>If you don’t have a parent (host), then there’s no need for the micro-frontend design.</strong></blockquote><h4>Classical build-time approach</h4><p>To build an web app, we normally put all codes in a folder, and ask the bundler (ex. webpack) to stitch them together into a single piece of code. We load this whole piece and when we need to display page A, we then flip a flag to render page A on the screen. This is referred as the classical build-time approach, meaning the bundle is prepared and loaded before the app starts. Even in the modern days, this is the by-default approach how most of the websites are built and delivered to the internet.</p><p>There’s also a small variation to it, that is to split this piece of code into multiple chunks so that it can reduce the load time. For example, page A can be split into another file (chunk) out of the main piece. It boosts the performance for loading the website, however, this doesn’t change the fact that this is a build-time approach. Because from the browser perspective, it still sees all files loaded at the beginning.</p><blockquote>The key point of the build-time approach is that the page A source code is ready to be called at all time no matter whether the app need it or not.</blockquote><h4>Runtime approach</h4><p>What if we don’t want to make page A content available at all time, or at least not at the beginning? For instance, page A could be composed of a large chunk of functionalities that we only want to access it when we need to later.</p><p>This comes to the runtime approach. The key to the runtime approach is that the page A (or B) needs to be fetched through the internet just as another web resource that would establish the communication with the host website after resolved. Retrospectively this is how the main app is built and loaded, and we just want to apply it to a page (or a component).</p><p>Luckily the webpack team has made this runtime approach working, and the low level logic has been implemented in what’s referred as the module federation:</p><pre>// Page A repo<br>// webpack.config.js<br><br>module.exports = {<br>  ...<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &#39;pagea&#39;,<br>      filename: &#39;remoteEntry.js&#39;,<br>      remotes: {<br>        &#39;./App&#39;: &#39;./src/App&#39;,<br>      },<br>    }),<br>  ],<br>  ...<br>};</pre><p>The above piece is written in the webpack.config.js for page A repo. <em>Notice we have multiple repos and each repo carries its own </em><em>webpack now.</em></p><p>Here, we use the module federation approach to split the page A App into a chunk file and save the registry info into another file remoteEntry.js. If you open the browser, you can see your app as usual. Additionally you can access to this registry file via your server (ex. localhost:3002/remoteEntry.js).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjDwjiR7YcGZY4e_6TqCUw.png" /></figure><p>A <strong>remote</strong>, each entry in the remotes array,<strong> </strong>refers to a module that can be exposed to as a web url. In our example, pagea/App is a remote (or a module). You can have multiple remotes exposed from a single registry, and here we only have one App per page.</p><p>Now, we need to consume this remote from the main repo, call it a shell app:</p><pre>// Shell main repo<br>// webpack.config.js<br><br>module.exports = {<br>  plugins: [<br>    new ModuleFederationPlugin({<br>      name: &#39;shell&#39;,<br>      remotes: {<br>        pagea: &#39;pagea@http://localhost:3002/remoteEntry.js&#39;,<br>      },<br>    }),<br>  ],<br>};</pre><p>When we launch the app from the shell, it loads the registry file remoteEntry at the beginning, but the difference now is that, it doesn’t load the App module from pageA, not yet. <em>Module and remoteEntry are two different files.</em></p><p>The registry file is only to try to establish the communication for the future, it includes global variables window.pageA in the high level:</p><pre>window.pageA = {<br>  init: {},<br>  get(module): {}<br>}</pre><p>This file doesn’t have pageA content. But it has some utility function so that the page knows how to init as well as get(module) the real content from. It also serves as the caching so that the browser wouldn’t request a new copy each time we need this module. It contains a lot more stuff since the file size of this registry isn’t extremely small as you might think.</p><p>With this setup, the shell app, hosted at localhost:3001 (not 3002) is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9tA4Eh0zu3Y2Qq758H9mA.png" /></figure><p>To demonstrate the runtime loading of page A, we have a prefetch button installed inside the shell app. When it is clicked, a new call to fetch page A content happens, which fetches the App module via url localhost:3002/src_App_js . Notice this is the real content resource hosted on page A server. Essentially by default the remote register file is loaded initially, afterwards we can load module content via the remote url on demand.</p><p>Also by default no matter how many times we fetch the page A, it wouldn’t cause another fetch of the resource through the internet. Both the registry and the module are fetched once and then cached afterwards. Imaging the page A is pretty big, as long as we can defer the loading of the page A, it can tremendously reduce the initial loading of the whole application.</p><p>I hope by far we get a snippet idea on how to load page content at runtime and why we are having the micro-frontend setup. Now let’s turn to see the detailed code of the shell app.</p><h4>Webpack import</h4><p>Within the shell, we need to import the page A at one point and this is done via a statement import :</p><pre>import React, { Suspense, useState } from &quot;react&quot;;<br>const PageA = React.lazy(() =&gt; import(&quot;pagea/App&quot;));<br><br>const App = () =&gt; {<br>  const [displayed, setDisplayed] = useState(false);<br><br>  const onPrefetch = () =&gt; {<br>    import(&quot;pagea/App&quot;);<br>  };<br><br>  const onDisplay = () =&gt; {<br>    setDisplayed(true);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;<br>        &lt;h1&gt;Shell&lt;/h1&gt;<br>        &lt;button onClick={onPrefetch}&gt;prefetch page A&lt;/button&gt;<br>        &lt;button onClick={onDisplay}&gt;display page A&lt;/button&gt;<br>      &lt;/div&gt;<br>      {displayed &amp;&amp; (<br>        &lt;Suspense fallback={&quot;loading...&quot;}&gt;<br>          &lt;PageA /&gt;<br>        &lt;/Suspense&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>Fetching of page A happens at the line of import(&quot;pagea/App&quot;). Since we can lazy load a resource, we can wrap it into a component such as PageA via React.lazy:</p><pre>const PageA = React.lazy(() =&gt; import(&quot;pagea/App&quot;));</pre><p>When PageA component is displayed, it’ll then fetch the content. This is React, since this is React component. But actually the real magic has nothing to do with React, it’s mostly handled by the import . Say we fetch the page A upon a mouse click:</p><pre>  const onPrefetch = () =&gt; {<br>    import(&quot;pagea/App&quot;);<br>  };</pre><p>That’s about it. You should be able to come up your own way of getting page A displayed from now on.</p><h4>Bonus</h4><p>Have you wondered how the statement import finds out what is the string pagea/App and launches the url accordingly. Of course we know the registry file documents it, but how does it know where to find the registry file via import statement?</p><p>This is because import statement is not provided by the language Javascript (not the same one), instead it’s a function that has been amended and provided by webpack. Once the registry file is loaded into a global variable window.pageA, it then remembers all the remotes. This way, it can recognize what pagea/App refers to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf47358c8fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Read music sheet easily with the help of CSS stylesheet]]></title>
            <link>https://windmaomao.medium.com/read-music-sheet-easily-with-the-help-of-css-stylesheet-b9004a01a677?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9004a01a677</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 14:36:04 GMT</pubDate>
            <atom:updated>2025-09-16T14:36:04.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Td-nDjQ5LgTLC6xRqZNZJQ.png" /></figure><p>I started to play piano couple of month ago, but sometimes after I skip playing for a week or two, I tend to forget all the notes. Damn, it’s really hard and annoying to pick it up again especially when you really need it. This is exactly like learning a new language, you thought you remembered them but you didn’t.</p><p>So this time, I’d like to create something that can help me to memorize them on my free time, so when I get back to play it again, I don’t find it too time-consuming for recognizing them.</p><p>Here’s what I come up with.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fembed%2Fpreview%2FvENobME%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DvENobME&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fpen%2FvENobME&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FvENobME-512.jpg%3Fversion%3D1758031332&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d246d55234d287d50139d3a9431c96f4/href">https://medium.com/media/d246d55234d287d50139d3a9431c96f4/href</a></iframe><p>Basically, it’s pretty simple. You hover on it, and check whether you get the right answer. Let me explain how CSS stylesheet can be used for displaying the sheet.</p><h4>Space and bar</h4><pre>&lt;div id=&quot;sheet&quot;&gt;<br>  &lt;div class=&quot;space&quot; note=&quot;G&quot;&gt;&lt;/div&gt;<br>  &lt;div class=&quot;space bar&quot; note=&quot;F&quot;&gt;&lt;/div&gt;<br>  ...<br>&lt;/div&gt;</pre><p>The sheet is pretty much made of spaces and bars and repeats this pattern forever. The trick here is that you can’t treat the bar as a horizontal line, because otherwise you don’t have enough space to hover on it. <strong>A space and a bar takes equal space vertically</strong>. Here’s the stylesheet for them:</p><pre>.space {<br>  width: 100%;<br>  height: 10px;<br>  position: relative;<br>}<br><br>.bar::before {<br>  content: &quot; &quot;;<br>  position: absolute;<br>  width: 100%;<br>  border: 1px solid black;<br>  top: 45%;<br>}</pre><p>The difference between a bar and a space is that a bar has a horizontal line draw in the middle. Here I used ::before pseudo element so that I don’t need to create an extra one.</p><p>Ok, in order to display the note when I hover, a small Javascript utility is attached:</p><pre>const note = document.getElementById(&quot;note&quot;);<br>function mouseover(e) {<br>  const el = e.target;<br>  note.textContent = el.getAttribute(&quot;note&quot;) || &quot;hover&quot;;<br>}<br><br>const sheet = document.getElementById(&quot;sheet&quot;);<br>sheet.childNodes.forEach((c) =&gt; {<br>  c.addEventListener(&quot;mouseover&quot;, mouseover);<br>});</pre><p>Basically whenever each one is hovered, it’ll display its corresponding note to an element called note .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*G8_Mv-7_KWy9RhV_bpxbkw.png" /></figure><p>We also need to add the stylesheet for displaying the symbol <em>O</em>:</p><pre>.space:hover {<br>  border: 1px dashed lightblue;<br>  padding: 1px 0;<br>}<br>.space:hover::after {<br>  content: &quot;o&quot;;<br>  font-size: 36px;<br>  display: flex;<br>  flex-direction: column;<br>  width: 100%;<br>  height: 100%;<br>  align-items: center;<br>  justify-content: center;<br>  margin-top: -2px;<br>  transform: rotate(30deg);<br>}</pre><p>It seems there’s quite a bit code, but it’s more about dealing with formatting the letter <em>O</em> slightly better in the middle of the vacant space. I aslo add some visual cue (via border) so that you know where the mouse cursor is hovered at.</p><p>That’s pretty much about it, except there’s a middle C which is slightly special therefore small additional style for it:</p><pre>.bar.mini {<br>  width: 20%;<br>}</pre><p>Alright. I hope you will find this piece useful if you need to deal with the music sheet.</p><p>Tip: no matter how you think you remember the music sheet phrase such as “EGBDF” or “FACE”, it doesn’t really help. Because in order to read music sheet, you need to know exact note in exact location under 100ms (maybe faster). So you need to do it without reasoning.</p><p>This is the tool to help you achieve that if you can spend at least 5min with it every day. You can also use a pencil or paper, no shame. I just happen to know how to use computer screen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9004a01a677" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When do we apply a card flipping animation to your family album?]]></title>
            <link>https://windmaomao.medium.com/when-do-we-apply-a-card-flipping-animation-to-your-family-album-989148fada2f?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/989148fada2f</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Wed, 10 Sep 2025 19:40:57 GMT</pubDate>
            <atom:updated>2025-09-10T19:40:57.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xl3SmVJXYYJ0dpk-2c52wA.png" /></figure><p>Don’t we like small animations here and there, such as card flipping? It turns out you don’t need an animation library to support that, because CSS has native support, we just need to know how to use it.</p><p>Recently I got a chance to work on a memory matching game where you pick two cards at a time, and if they don’t match you flip again until you reveal all the cards. That’s it, if you want, you can <a href="https://www.fjin.online/resume#flip">play the game here</a>. I believe half of the time is cards with cats and half of the time with dogs.</p><p><strong>Two sides</strong></p><p>To demo or study this flipping animation easier, I created the following <a href="https://codepen.io/windmaomao/pen/qEOvGLq">Pen</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fembed%2Fpreview%2FqEOvGLq%3Fdefault-tabs%3Dcss%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DqEOvGLq&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fpen%2FqEOvGLq&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FqEOvGLq-512.jpg%3Fversion%3D1757375037&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/31fac38a8f47bd398fffc832366a7481/href">https://medium.com/media/31fac38a8f47bd398fffc832366a7481/href</a></iframe><p>The structure of HTML is minimal:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;card&quot;&gt;<br>    &lt;div class=&quot;front&quot;&gt;Front&lt;/div&gt;<br>    &lt;div class=&quot;back&quot;&gt;Back&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>You need to have two sides of card, one front and one back in a container where its position is set to be relative , since we need to put a card inside.</p><pre>.container {<br>  width: 160px;<br>  height: 200px;<br>  position: relative;<br>}</pre><p>The card is then placed inside with position absolute and set to cover the whole space. Everything is normal and the special part is the transform-style.</p><pre>.card {<br>  position: absolute;<br>  width: 100%;<br>  height: 100%;<br>  transform-style: preserve-3d;<br>}</pre><p>This is a relatively new css attribute (maybe not that new) which essentially is saying the children element can be transformed in a 3D space now.</p><p>We can place the front side inside the card:</p><pre>.front {<br>  position: absolute;<br>  width: 100%;<br>  height: 100%;<br>  backface-visibility: hidden;<br>  background: red;<br>  color: white;<br>}</pre><p>Any content can be added to the front side. Here we set its background to red , and text to be white . We also set the backface-visibility to hidden . This means the background of this surface isn’t transparent, so whatever placed under it can’t be seen, just like a regular physical card placed on a table. No kidding!</p><p>Alright, now we can place the back side inside the card as well.</p><pre>.back {<br>  position: absolute;<br>  width: 100%;<br>  height: 100%;<br>  backface-visibility: hidden;<br>  background: blue;<br>  color: white;<br>  transform: rotateY(180deg);<br>}</pre><p>The background is set to blue and text white to make sure we can differentiate the front and the back easily. We also turn the back side to be 180 degree in the y axis. Basically it means the backside of the card is facing downward. Since we also set the backface-visibility to be hidden , if we ever flip the card to make it the front one, we can’t see the other side either. This is exactly like flipping the card that is rest on a table. The only difference is that we make sure there’re two sides of it.</p><h4>Flip the card</h4><p>Now we have every pieces of this puzzle, all we need is to flip the card and hopefully we can see some animation as well. We can associate the flip action with any event, here let’s do the basic one, such as on the mouse hover:</p><pre>.container:hover .card {<br>  transform: rotateY(180deg);<br>}</pre><p>Upon the mouse hover to the container, we want the whole card (with the front and the back side) to flip 180 degrees in y axis. In order to make it animated, we can let the card know:</p><pre>.card {<br>  ...<br>  transform-style: preserve-3d;<br>  transition: all 0.5s ease;<br>}</pre><p>That’s it.</p><p>Now, when you hover on it, it’ll flip the card left to right in a smooth animation. And the best part, if you un-hover on it, it’ll stop the animation and start to revert back to be the old un-revealed card again.</p><p>Amazing! Hope this helps you a bit next time when you need a card flipping experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=989148fada2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phone input field with cursor placement in React]]></title>
            <link>https://windmaomao.medium.com/phone-input-field-with-cursor-placement-in-react-284ffabb5bfa?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/284ffabb5bfa</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 15:20:53 GMT</pubDate>
            <atom:updated>2025-08-26T15:20:53.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5BScU52u7Y9IZ0sQ" /><figcaption>Photo by <a href="https://unsplash.com/@wesley_squared?utm_source=medium&amp;utm_medium=referral">Wesley Hilario</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lately I got an request for making a phone input which renders the format of (111)222-3333. I kinda of struggled slightly so want to clarify the key points in this article. You can play with the following code first to get an idea what this phone input does.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fembed%2Fpreview%2FZYbjKKx%3Fdefault-tabs%3Djs%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DZYbjKKx&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fpen%2FZYbjKKx&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FZYbjKKx-512.jpg%3Fversion%3D1756216168&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5ba957885e9f127176889e4d66482c5/href">https://medium.com/media/f5ba957885e9f127176889e4d66482c5/href</a></iframe><h4>Input</h4><p>A phone input is an input, so we would want to wire with the regular value/onChange pair of any react input:</p><pre>&lt;input value={inputValue} onChange={onChange} /&gt;</pre><p>The solution you come up with can quickly reach to a function that post-processes the user input:</p><pre>function processPhoneInput(str) {<br>  let res = str.replace(/\D/g, &quot;&quot;).slice(0, 10);<br>  if (res.length &gt; 6) {<br>    res = res.slice(0, 6) + &quot;-&quot; + res.slice(6);<br>  }<br>  if (res.length &gt; 3) {<br>    res = &quot;(&quot; + res.slice(0, 3) + &quot;)&quot; + res.slice(3);<br>  }<br>  return res;<br>}</pre><p>What this function does is to take any string, such as (111)2 , strip out all the non-number characters and then add - after the sixth digit, and then wrap the first three digits with a bracket() .</p><p>You might write it a bit verbose, but that’s ok. The key take-away here is that Javascript string does support replace and slice out of the box, so you don’t have to convert the string into an array before doing all the manipulation. After that you can wire this function in the onChange event:</p><pre>  const onChange = (e) =&gt; {<br>    const { value, selectionStart, selectionEnd } = e.target;<br>    const processed = processPhoneInput(value);<br>    setInputValue(processed);<br>  };</pre><p>Basically take the raw user input and post-process it before updating the input value.</p><h4>Cursor</h4><p>There’s only one major problem with this straight-forward input design. When you remove a digit using a del, or select a portion of digits and hit del , it could mess up your current cursor location, that you can’t maintain the native input behavior any more. Very annoying actually.</p><p>In order to fix it, we need to know the current cursor location before the action, as well as the new cursor location after the action. We need to rely on the native input method, therefore we need a ref. Here’s the complete code:</p><pre>function App() {<br>  const ref = useRef();<br>  const [inputValue, setInputValue] = useState(&quot;&quot;);<br>  const onChange = (e) =&gt; {<br>    const { value, selectionStart, selectionEnd } = e.target;<br>    const processed = processPhoneInput(value);<br>    setInputValue(processed);<br>    setTimeout(() =&gt; {<br>      const pos =<br>        processed.indexOf(<br>          value[selectionStart - 1], <br>          selectionEnd - 1<br>        ) + 1 || selectionEnd;<br>      ref.current.selectionStart = pos;<br>      ref.current.selectionEnd = pos;<br>    }, 0);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h4&gt;Phone Number&lt;/h4&gt;<br>      &lt;input ref={ref} value={inputValue} onChange={onChange} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We wire a manual ref to the input element and we use it to dig into the selectionStart and selectionEnd properties that controls the input selection at all time.</p><pre>const pos =<br>        processed.indexOf(<br>          value[selectionStart - 1], <br>          selectionEnd - 1<br>        ) + 1 || selectionEnd;</pre><p>The new cursor pos is determined by searching the beginning of the current selection inside the processed string starting the end of the current selection. Wherever that location is should gives us the correct cursor location. I guess the reason why this works is that the processed string is always longer than the raw digits.</p><p>And we get the new cursor location, we can make a cursor change by setting both selectionStart and selectionEnd with a setTimeout call , this way we can make sure the cursor updates after the react finishes the current render cycle.</p><p>That’s it. Have fun. Let me know if you have other solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=284ffabb5bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS sticky position can be messy, why?]]></title>
            <link>https://windmaomao.medium.com/css-sticky-position-can-be-messy-why-808ba96cf4ce?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/808ba96cf4ce</guid>
            <category><![CDATA[sticky]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 13:06:58 GMT</pubDate>
            <atom:updated>2025-08-22T13:06:58.323Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dEcG_8zIF8VMn6nQ" /><figcaption>Photo by <a href="https://unsplash.com/@ukterryg?utm_source=medium&amp;utm_medium=referral">Terry Granger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Css has published sticky position quite a while ago, however I never understood how to use it effectively, especially on when it’s working and when it’s not. In this quick article, I’d like to point out why.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fembed%2Fpreview%2FemprvYR%3Fdefault-tabs%3Dcss%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DemprvYR&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fwindmaomao%2Fpen%2FemprvYR&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FemprvYR-512.jpg%3Fversion%3D1755799782&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/387e798a2e4da89fa9199cb1e67d0359/href">https://medium.com/media/387e798a2e4da89fa9199cb1e67d0359/href</a></iframe><h4>Sticky</h4><p>You can first give the above demo some play because it’s a working case. We can have one section containing a navbar and some content.</p><pre>&lt;div&gt;<br>  &lt;div class=&quot;navbar&quot;&gt;Navbar 1&lt;/div&gt;<br>  &lt;div class=&quot;content&quot;&gt;Content&lt;/div&gt;<br>&lt;/div&gt;</pre><p>The goal is when we scroll through the rest of the content, we’d love to have the navbar sticky to the top of the screen. There’re more than one key element to make it work, believe it or not.</p><pre>.navbar {<br>  ...<br>  height: 50px;<br>  position: sticky;<br>  top: 0;<br>}</pre><p>The sticky navbar needs to have a position set to sticky and an absolute position value, such as top: 0 . This is the “sticking” point. For example, top: 0 would mean the element sticks to the top of the viewport when it reaches that position.</p><p>There’re three identities here: sticky element, container that supports the scroll (in our case, body) and a parent of the sticky element (that unnamed div). We need to understand what is the goal here. We want to stick navbar to the top when we scroll through the rest of <strong>content ! </strong>This means the content is as important as the sticky navbar.</p><pre>.content {<br>  height: 150px;<br>  background: grey;<br>}</pre><p>This means to setup a typical sticky case, you need to have a parent div . Inside it, the first element is the sticky element, and the rest of them are content that requires a bit more height or space to scroll through. This is important, because otherwise the effect won’t be visible since the content doesn’t have time to appear to be scrolled through. So in general, you should have decent amount of content in space comparing to the sticky header.</p><p>Now comes to another interesting question, how do we dismiss a sticky element, so that it can be non-sticky any more.</p><h4>Non-sticky</h4><p>You have multiple sections where each section has a sticky element. How and why does each sticky appear and disappear? This goes back to the parent of the sticky element once again.</p><p>We are scrolling the parent (along with what’s inside the parent) through a scrolling container (such as body). Without the sticky element, you basically scroll everything as normal. With the sticky element, whenever a threshold of the stickiness is detected, the sticky element (defined inside) will pop out to serve as position: fixed while the rest of elements (such as content) behave intact. This means, the rest of the page can continue scrolling as before, like nothing happens. And after the parent moves out of the viewport, the sticky element finishes its purpose, because my mother is gone. At that time, it goes back to be position: relative . During the whole cycle of sticking, the position value of that element flips back and forth, in concept.</p><p>So the simplest way to have multiple non-conflicting sticking elements is to have multiple sections where each section has a sticking element.</p><pre>&lt;div&gt;<br>  &lt;div class=&quot;navbar&quot;&gt;Navbar 1&lt;/div&gt;<br>  &lt;div class=&quot;content&quot;&gt;Content&lt;/div&gt;<br>&lt;/div&gt;<br>&lt;div&gt;<br>  &lt;div class=&quot;navbar2&quot;&gt;Navbar 2&lt;/div&gt;<br>  &lt;div class=&quot;content&quot;&gt;Content&lt;/div&gt;<br>&lt;/div&gt; </pre><p>I’m sure there’re more complicated version that you can setup to have multiple sticking elements. But once you understand the basic, it’ll help you figure out why the screen is doing that. For instance, if a parent is still in the viewport, its sticky element will still be visible as sticking after the threshold is detected. This means you could have multiple sticking elements on the screen at the same time. The only reason why one is showing up on top of another one will be controlled by z-index.</p><p>Hope this helps you to de-mythify what is the CSS sticky position.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=808ba96cf4ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useActionState hook to handle form action]]></title>
            <link>https://windmaomao.medium.com/useactionstate-hook-to-handle-form-action-04a8b33b0856?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/04a8b33b0856</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 16:58:20 GMT</pubDate>
            <atom:updated>2025-08-13T16:58:20.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>useActionState hook to handle form submission</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5UGjMjGC9it1vYYR" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have used multiple different ways to handle the form submission in the past. But lately I have studied useActionState hook and applied to form without any third party library or your own custom coding. This actually surprised me slightly, because I didn’t know there’s a native hook from React codebase that can allow me to do that before.</p><pre>import { useActionState } from &quot;react&quot;;<br><br>async function increment(previousState, formData) {<br>  return previousState + 1;<br>}<br><br>function StatefulForm({}) {<br>  const [state, formAction] = useActionState(increment, 0);<br>  return (<br>    &lt;form action={formAction}&gt;<br>      ...<br>    &lt;/form&gt;<br>  )<br>}</pre><p>Out of the syntax, useActionState is a hook, and it provides a function formAction to a typical form. The form submission can be triggered by the form submission (a button).</p><p>We normally would write this action function ourselves. For simple form, it’s pretty straightforward and we could even prevent the form to redirect us to reload the page if we want to.</p><p>Here we did provide the original form handler increment to the hook. So essentially useActionState takes the original handler and provide a wrapper handler. And the utility it provides is the additional form state as returned from the first element.</p><p>This comes the first interesting thing of this hook. <strong>It allows you to define the state shape, whatever the way we want to.</strong> In this case, we just want a simple counter to indicate the form data, which is 0 initially and then every time we submit the form, we increment the state from the previousState this hook stores. This is where this hook gets the name, you could also think this as useFormState (I believe this is its original name).</p><p>Other than the previousState , stored inside the hook, the formData that is submitted via the classical form element is passed along to the form handler.</p><pre>function action(currentState, formData) {<br>  // ...<br>  return &#39;next state&#39;;<br>}</pre><p>Our increment handler doesn’t do much, it actually ignores the formData and return the new state after incrementing the current state. But here’s more complicated example:</p><pre>export async function addToCart(prevState, queryData) {<br>  const itemID = queryData.get(&#39;itemID&#39;);<br>  if (itemID === &quot;1&quot;) {<br>    return &quot;Added to cart&quot;;<br>  } else {<br>    // Add a fake delay to make waiting noticeable.<br>    await new Promise(resolve =&gt; {<br>      setTimeout(resolve, 2000);<br>    });<br>    return &quot;Couldn&#39;t add to cart: the item is sold out.&quot;;<br>  }<br>}</pre><p>From this example, the first thing you notice is that <strong>the handler is an </strong><strong>async function</strong>, that means you can implement any promise like algorithm inside. Essentially this function could take a while to execute if you want it to be. Inside the function, <strong>we can query the form data </strong><strong>queryData via api </strong><strong>get</strong> . And since the shape of the state is up to you, in this case, <strong>we return a error message to indicate this form isn’t ready to be submitted</strong>.</p><p>From here, you can see that you can define any data format as you want to facilitate your complex form handling. You can have your own validation schema embedded as well.</p><p>The following is a more complicated example, where we use a server form action bundled with validation via zod schema:</p><pre>import { z } from &#39;zod&#39;;<br><br>const FormSchema = z.object({<br>  id: z.string(),<br>  customerId: z.string({<br>    invalid_type_error: &#39;Please select a customer.&#39;,<br>  }),<br>  amount: z.coerce<br>    .number()<br>    .gt(0, { message: &#39;Please enter an amount greater than $0.&#39; }),<br>  status: z.enum([&#39;pending&#39;, &#39;paid&#39;], {<br>    invalid_type_error: &#39;Please select an invoice status.&#39;,<br>  }),<br>  date: z.string(),<br>});<br><br>const CreateInvoice = FormSchema.omit({ id: true, date: true });<br><br>export type State = {<br>  errors?: {<br>    customerId?: string[];<br>    amount?: string[];<br>    status?: string[];<br>  };<br>  message?: string | null;<br>};<br><br>export async function createInvoice(prevState: State, formData: FormData) {<br>  const validatedFields = CreateInvoice.safeParse({<br>    customerId: formData.get(&#39;customerId&#39;),<br>    amount: formData.get(&#39;amount&#39;),<br>    status: formData.get(&#39;status&#39;),<br>  });<br><br>  // If form validation fails, return errors early. Otherwise, continue.<br>  if (!validatedFields.success) {<br>    return {<br>      errors: validatedFields.error.flatten().fieldErrors,<br>      message: &#39;Missing Fields. Failed to Create Invoice.&#39;,<br>    };<br>  }<br><br>  // Prepare data for insertion into the database<br>  const { customerId, amount, status } = validatedFields.data;<br>  const amountInCents = amount * 100;<br>  const date = new Date().toISOString().split(&#39;T&#39;)[0];<br><br>  // Insert data into the database<br>  try {<br>    await sql`<br>      INSERT INTO invoices (customer_id, amount, status, date)<br>      VALUES (${customerId}, ${amountInCents}, ${status}, ${date})<br>    `;<br>  } catch (error) {<br>    // If a database error occurs, return a more specific error.<br>    return {<br>      message: &#39;Database Error: Failed to Create Invoice.&#39;,<br>    };<br>  }<br><br>  revalidatePath(&#39;/dashboard/invoices&#39;);<br>  redirect(&#39;/dashboard/invoices&#39;);<br>}</pre><p><strong>Another interesting thing about this hook is that it can be run at server side </strong>as long as the form submission goes to the server.</p><p>Alright, that’s about the useActionState hook, to make your life easier, I also highlighted all the usage of it. Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04a8b33b0856" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Suspense bundled with Server Components]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://windmaomao.medium.com/react-suspense-bundled-with-server-components-9c13bde7d627?source=rss-f6ef5f80c131------2"><img src="https://cdn-images-1.medium.com/max/2600/0*Pj3qaS_rtk5SUI1M" width="5127"></a></p><p class="medium-feed-snippet">I have known React Suspense for quite some time, maybe since it was born. However I didn&#x2019;t adopt it right away because I didn&#x2019;t find it&#x2026;</p><p class="medium-feed-link"><a href="https://windmaomao.medium.com/react-suspense-bundled-with-server-components-9c13bde7d627?source=rss-f6ef5f80c131------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://windmaomao.medium.com/react-suspense-bundled-with-server-components-9c13bde7d627?source=rss-f6ef5f80c131------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c13bde7d627</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-server-component]]></category>
            <category><![CDATA[suspense]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Fang Jin]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 15:21:02 GMT</pubDate>
            <atom:updated>2025-08-08T15:21:02.870Z</atom:updated>
        </item>
    </channel>
</rss>