<?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 Howard on Medium]]></title>
        <description><![CDATA[Stories by Howard on Medium]]></description>
        <link>https://medium.com/@anokyy?source=rss-78cc115efee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RG056qbW_RTbIlW9</url>
            <title>Stories by Howard on Medium</title>
            <link>https://medium.com/@anokyy?source=rss-78cc115efee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:07:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anokyy/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[The easiest way to prefetch links and fix fetch waterfalls in react-query, useSWR, Apollo-client or…]]></title>
            <link>https://medium.com/@anokyy/the-easiest-way-to-prefetch-links-and-fix-fetch-waterfalls-in-react-query-useswr-apollo-client-or-33ae59409bf4?source=rss-78cc115efee------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ae59409bf4</guid>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Howard]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 09:54:23 GMT</pubDate>
            <atom:updated>2022-07-03T11:20:03.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>The easiest way to prefetch links and fix fetch waterfalls in react-query, useSWR, Apollo-client or RTK Query</h3><h3>TL;DR</h3><p>This article introduces how to use <a href="https://github.com/oney/react-prefetching">react-prefetching</a> package with 3 steps to <strong>prefetch hovered links</strong> and <strong>fix fetch waterfalls</strong>, which make your apps lightning fast.</p><h3>Fetch waterfalls</h3><p><a href="https://github.com/TanStack/query">react-query</a>, <a href="https://github.com/vercel/swr">swr</a>, <a href="https://www.apollographql.com/docs/react/">Apollo-client</a> and <a href="https://redux-toolkit.js.org/rtk-query/overview">RTK Query</a> are most popular libraries to fetch data in React apps, but fetch waterfalls normally would happen in these Fetch-on-Render libraries and is hard to fix.</p><p>Say your app is using <a href="https://reactrouter.com/">react-router</a> and react-query like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33e2fd12705403521a853b0af21b4be1/href">https://medium.com/media/33e2fd12705403521a853b0af21b4be1/href</a></iframe><p>Assume fetchA, fetchB, fetchC all take 1 second to fetch. When opening the url /a,</p><ul><li>In 1 second, data of A shows, but B just starts fetching and shows loading.</li><li>In 2 seconds, data of A and B shows, but C just starts fetching and shows loading.</li><li>In 3 seconds, data of A, B and C shows.</li></ul><p>However, it’s totally doable that A, B and C start data fetching in the same time/in parallel, and in 1 second, data of A, B and C all shows.</p><p>This issue is called <a href="https://17.reactjs.org/docs/concurrent-mode-suspense.html#traditional-approaches-vs-suspense">fetch waterfalls</a>.</p><h3>Possible solutions</h3><ol><li>Use compiling tools like <a href="https://relay.dev/">Relay</a> to collect children queries to generate one GraphQL query.<br>But what if your backend doesn’t support GraphQL?</li><li>Use <a href="https://www.educative.io/answers/what-is-server-side-rendering">SSR</a> like <a href="https://remix.run/">Remix</a>, <a href="https://nextjs.org/">Next.js</a> to prepare data together in backend.<br>But what if your frontend app is purely <a href="https://medium.com/@prashantramnyc/server-side-rendering-ssr-vs-client-side-rendering-csr-vs-pre-rendering-using-static-site-89f2d05182ef">CSR</a> without a backend?</li><li><a href="https://twitter.com/housecor/status/1531642615283625984">Prefetch in the parent</a> with Fetch-on-Render libraries.<br>The problem of this approach is, the parent component needs to know what queries its child components fetch. The implementation would make the parent and children coupled together and is hard to maintain if having deeply nested children.</li></ol><h3>Better solution</h3><p>Is it possible to use our favorite Fetch-on-Render libraries (such as react-query, swr and Apollo-client) without causing fetch waterfalls?</p><p>Yes, use <a href="https://github.com/oney/react-prefetching">react-prefetching</a> package with 3 steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9b1849540ff5f454ff59deb08275992/href">https://medium.com/media/b9b1849540ff5f454ff59deb08275992/href</a></iframe><ol><li>Replace <a href="https://v5.reactrouter.com/web/api/BrowserRouter">BrowserRouter</a> from react-router-dom with PrefetchRouter from react-prefetching</li><li>Replace <a href="https://reactrouter.com/docs/en/v6/components/link">Link</a> and <a href="https://reactrouter.com/docs/en/v6/components/nav-link">NavLink</a> from react-router-dom with react-prefetching</li><li>In components, after uesQuery, if useIsPrefetch() is true, return the child components.</li></ol><p>That’s all!</p><p>Now, when A is rendered, its children B and C are also rendered in the <strong>prefetch universe</strong>, so the uesQuery of A, B and C are called <em>in the same render</em>. Then, when data of A is loaded and rendering of B is unlocked, the uesQuery of B already has data to show immediately because it has been triggered in the <strong>prefetch universe</strong> previously. So does C.</p><p>Fetch waterfalls issue is totally solved.</p><h3>Prefetch links</h3><p>You know what is better? You also empower your app with prefetching when users hover links in the second step above. That makes your frontend app look blazingly fast. No more loading spinners!</p><p>Normally if you want prefetching feature in your app, you need some SSR frameworks like <a href="https://web.dev/route-prefetching-in-nextjs/">Next.js</a> or <a href="https://remix.run/docs/en/v1/api/remix#prefetchpagelinks-">Remix</a> which introduce more complex architecture. But <a href="https://github.com/oney/react-prefetching">react-prefetching</a> does that with totally CSR and Fetch-on-Render libraries.</p><h3>How it works</h3><p>Remember I mentioned a <strong>prefetch universe</strong>?</p><p>If useIsPrefetch() is false, the component is just in the normal render tree that will be displayed visibly to users.</p><p>If useIsPrefetch() is true, it’s in the prefetch universe, so it skip any if (isLoading) return &lt;p&gt;Loading&lt;/p&gt;; to render child components to trigger their data fetching.</p><p>The above is to avoid fetch waterfalls. For prefetching links, when a user hovers a link, the onMouseEnter event handler of the link is invoked, and the prefetch universe is rendered with its url to trigger all queries, before the user really clicks it.</p><h3>Demo</h3><p>You can check a real demo in this <a href="https://codesandbox.io/s/react-prefetching-4lu8fh?file=/src/Main.tsx:1402-1416">codesandbox</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F4lu8fh&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F4lu8fh&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F4lu8fh%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/4209915af43475dd4a1d9736b7a72cbb/href">https://medium.com/media/4209915af43475dd4a1d9736b7a72cbb/href</a></iframe><p>This demo is based on <a href="https://reactrouter.com/docs/en/v6/getting-started/tutorial">the tutorial of react-router</a>. It is modified so the data fetching of queries takes 500 ms to load. When you play with Prefetch section, especially when clicking links with mouse, you would notice that the new page is displayed instantly because prefetching is working.</p><h3>Performance</h3><p>Maybe you would worry about the extra rendering cost of the <strong>prefetch universe</strong> that might hurt the performance. Even though I didn’t benchmark it, I’d say the performance isn’t hurt, because there are much fewer React.createElement() and vDOM diffing in the prefetch universe, comparing to the real displaying render tree.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ae59409bf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Turbo — the ultimate solution to optimize React performance]]></title>
            <link>https://blog.devgenius.io/react-turbo-the-ultimate-solution-to-optimize-react-performance-b666ca9db0b5?source=rss-78cc115efee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b666ca9db0b5</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Howard]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 06:57:27 GMT</pubDate>
            <atom:updated>2022-06-17T07:35:36.695Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Turbo — the ultimate solution to optimize React performance</h3><blockquote>I worked at Facebook as Front End Engineer and created ~4000 stars <a href="https://github.com/react-native-webrtc/react-native-webrtc">react-native-webrtc</a></blockquote><h3>TL;DR</h3><p><a href="https://github.com/oney/react-turbo">React Turbo</a> automatically optimizes React performance in compile time, so <strong>developers don’t need to do optimization manually.</strong></p><h3>Painfulness of React</h3><p>React is lovely to develop. JSX is better than template. Hooks are powerful for isolation and composition of business logic.</p><p>React almost has the best developer experience (DX) except for one thing: performance optimization.</p><h4>Change detection / Reactivity</h4><p>We have to admit that <a href="https://twitter.com/johnlindquist/status/1109498707475488768">React is <em>never</em> being reactive</a>. The strategy of <em>change detection(or Reactivity)</em> of React is based on <strong>diff (Value Comparison)</strong>. Comparatively, Vue, Angular and Svelte are based on <strong>Value Observing/Subscription</strong>.</p><h4>Value Comparison</h4><p><em>Value Comparison</em> means that:</p><ol><li>We need to <em>memoize and stabilize</em> values to <strong>avoid <em>unrelated</em> re-calculation</strong>; props to <strong>avoid <em>unrelated</em> re-rendering</strong>.</li><li>We can’t achieve <strong>fine-grained reactivity </strong>automatically because the <em>minimal level of reactivity</em> in React is Components (not Values or Elements).</li></ol><p>The issue 1. is why we need useMemo, useCallback, React.memo and even immutable data. We fix the issue 2. by subscription container like &lt;Controller render={( =&gt; /&gt; of <a href="https://react-hook-form.com/">react-hook-form</a>.</p><p>So, when we encounter the above 2 performance issues, we have to add useMemo, useCallback or wrap with &lt;Controller /&gt; <strong>manually</strong>.<br>And that’s awful.</p><h3>React Turbo</h3><p><a href="https://github.com/oney/react-turbo">React Turbo</a> is a babel plugin that converts the strategy of change detection of your React components <strong><em>from Value Comparison to Value Subscription</em></strong> in <strong>compile time</strong>. So it becomes fine-grained reactivity and caches all values to avoid unnecessary re-calculation and re-rendering.</p><p>After installing React Turbo, you don’t need to write any useMemo, useCallback and even use <a href="https://github.com/reduxjs/reselect">reselect</a> with Redux. Actually, you don’t have to modify/write any code to optimize performance.</p><h4>Installation</h4><p>Please check <a href="https://github.com/oney/react-turbo">the installation instruction in React Turbo repo</a>.</p><h3>vs. React Forget</h3><p>Sounds like <a href="https://www.youtube.com/watch?v=lGEMwh32soc">React Forget</a>, huh?</p><p>The different is React Forget is still based on V<em>alue Comparison</em>.</p><p>React Turbo is V<em>alue Subscription</em> that can achieve <em>fine-grained reactivity</em> in <strong>both value calculation and element rendering</strong>.<br>And React Forget still can’t achieve fine-grained reactivity. It just memoizes anything. Take an example:</p><h4>Value Comparison vs. Value Subscription</h4><p>Let’s say when you have a value text in Component A. And you pass text from A to component B, B to C, C to D,… , finally Y to Z. Then, a &lt;input value={text}/&gt; in Z uses text.</p><p>When text changes, even with React Forget, component A, B, C, … and Z all re-renders.<br>That means all variables and React elements in component A to Z are all <strong>re-initialized and re-created again to be compared</strong>, even though most of the values are the same (because only text changes).</p><h4>Overhead</h4><p>The <strong>overhead of the recreation and comparison</strong>(e.g. Vdom diff, useMemo, React.memo, or createSelector of reselect<strong>) </strong>of the-same-value variables and React elements hurts performance when you have a large app like the website of Facebook Ads Manager (yeah, I’ve worked on that codebase, and it’s painful and enjoyable 😉).</p><p>Especially when the value like text changes frequently as typing with 100–200ms per event, or even dragging slider (&lt;input type=&quot;range&quot;/&gt;) and color picker with 33 ms per event, users can feel the lagging.</p><p>With React Turbo that is Value Subscription, when text changes, only the &lt;input/&gt; in Z re-renders (Z won’t re-render) because only that &lt;input/&gt; <strong>subscribes</strong> text.</p><p><strong>No comparison happens.</strong></p><p>That’s what we call <strong>fine-grained reactivity</strong>.</p><h3>How it works</h3><p>Basically, it converts <em>states</em> <em>(</em>value from useState<em>)</em> from plain JavaScript values to observable/subscribable signals/atoms like <a href="https://recoiljs.org/">Recoil</a>, <a href="https://github.com/pmndrs/zustand">zustand</a> and <a href="https://effector.dev/">effector</a>.</p><p>Then automatically collecting dependencies of <em>variable declaration</em> in Component to generate computed atoms (like useMemo where linters hint missing dependencies).</p><p>And it also wraps <em>every</em> React.createElement with a subscription container <em>with its dependencies</em> (to achieve fine-grained reactivity on <strong>elements</strong>).</p><p>All of these are transformed in compile time.</p><h3>vs. MobX</h3><p>The differences are the values of MobX are mutable and the subscription happens and is decided <strong>in runtime</strong>.</p><p>The values of React Turbo are still immutable which work in concurrent mode and Value Subscription is decided in compile time.</p><h3>Future</h3><p>React Forget is a great move that optimizes performance in compile time, but Value Subscription absolutely has smaller overhead and better performance than Value Comparison. So I hope React core team can adopt the concept of React Turbo.</p><h3>Note</h3><ol><li>The components/hooks compiled by React Turbo can work with the components/hooks that is <strong>not</strong> compiled by React Turbo. So we don’t have to compile any <em>third party libraries</em> to work in a React Turbo app.</li><li>The bundle size of a React Turbo app won’t increase exponentially. Normally it only increases 10–20% just like you optimize manually by adding useMemo, useCallback.</li><li>The observable atoms in React Turbo are based on <a href="https://effector.dev/">effector</a> now.</li><li>React Turbo can easily solve the performance issue of useEvent wants to solve. The callback of React Turbo would still change and cause the subscribing component re-render, but <strong>because it’s fine-grained</strong>, it won’t hurt performance.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b666ca9db0b5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/react-turbo-the-ultimate-solution-to-optimize-react-performance-b666ca9db0b5">React Turbo — the ultimate solution to optimize React performance</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[為何 useEvent 是個糟糕的方案？(更好的在這)]]></title>
            <link>https://medium.com/@anokyy/%E7%82%BA%E4%BD%95useevent%E6%98%AF%E5%80%8B%E7%B3%9F%E7%B3%95%E7%9A%84%E6%96%B9%E6%A1%88-%E6%9B%B4%E5%A5%BD%E7%9A%84%E5%9C%A8%E9%80%99-de7fc2e509e8?source=rss-78cc115efee------2</link>
            <guid isPermaLink="false">https://medium.com/p/de7fc2e509e8</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Howard]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 02:52:46 GMT</pubDate>
            <atom:updated>2022-06-02T06:43:04.949Z</atom:updated>
            <content:encoded><![CDATA[<p>React官方最近推出了 useEvent RFC，乍看之下似乎解決了很多 callback 在functional component 的問題，然而，useEvent 在我看來不是一個完美的解決方案，需要開發者寫更多 code，心智負擔更重，code 更醜了，容易有 bug，卻無法解決所有問題。</p><p>本文將會解釋 useEvent 的缺點，並試圖給出一個更好的解決方案。</p><h3>useEvent RFC</h3><p><a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md">官方連結在此</a>，建議先行閱讀 RFC，再看此文。</p><p>綜觀全 RFC，基本上只解決了兩個問題：<br>1. 提供穩定引用 callback，使 child component 不會無謂 re-render<br>2. 讓 closure 能取到 latest values 而非 outdated values</p><p>然而這兩個問題都沒有被完美解決。</p><h3>穩定引用 callback (stable identity callback)</h3><p>useEvent 提供了引用不變的 callback，RFC 給出了<a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#basic-example">一個範例</a>：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9a09f72655132a74cdd00a71dbff475/href">https://medium.com/media/b9a09f72655132a74cdd00a71dbff475/href</a></iframe><p>缺點有：</p><h3>1. useEvent 無法優化 inline callback</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/163c36cc8524085c64d576222d5c21ee/href">https://medium.com/media/163c36cc8524085c64d576222d5c21ee/href</a></iframe><h3>2. 為了優化，需要重複寫 useEvent 多次</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46938a9cce3780f5e92b0baf1110bea5/href">https://medium.com/media/46938a9cce3780f5e92b0baf1110bea5/href</a></iframe><h3>3. 在條件中給出不同 callback，優化會失效</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/256c36baf59e94c4eb156b74f2355ebd/href">https://medium.com/media/256c36baf59e94c4eb156b74f2355ebd/href</a></iframe><h3>4. 對於 library 提供的組件，library 使用者需要知道哪些 props 可以提供 useEvent 過的callback</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9681de0f6714952d2dbf60f97c3732fb/href">https://medium.com/media/9681de0f6714952d2dbf60f97c3732fb/href</a></iframe><p>若 submit 被用在 render，<a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#functions-called-during-render-still-use-usecallback">依照 useEvent RFC所提，會 throw error</a>。</p><p>這四個問題，useEvent 是無法、或要更複雜的 code 才能解決。</p><h3>更好的解決方案</h3><p>試試看這個套件 <a href="https://github.com/oney/react-with-stable">react-with-stable</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/125d606316c79e97d1e3492b030aee04/href">https://medium.com/media/125d606316c79e97d1e3492b030aee04/href</a></iframe><p>用 withStable HOC（高階組件）包住 SendButton，然後宣告 onClick 是只會在事件中被呼叫，這就是全部需要增加的 code 了！<br>其他什麼都不用做就可以享受到性能優化。</p><h3>1. 可以優化 inline callback</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf41917e87bad5caec539f695a590729/href">https://medium.com/media/bf41917e87bad5caec539f695a590729/href</a></iframe><h3>2. 幾乎不需要改動原有 code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30ebab54669c33574d0a68cd5ea550f1/href">https://medium.com/media/30ebab54669c33574d0a68cd5ea550f1/href</a></iframe><p>依照我在臉書工作的經歷，公司內部有自己的 React UI framework，比如說一個框架提供了 GeoButton component，有幾千個 components 使用了 GeoButton，為了要上 useEvent ，那這幾千個組件都要 refactor，這應該很難用寫 script 自動修改。（雖然說讓程序員有了工作 lol）</p><p>相較之下 withStable 方案，只需要包一次，幾千個 components 都被優化了。<br>真正 wrap once, optimize anywhere.</p><h3>3. 在條件中給出不同 callback，優化也生效</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea7afaccf1162d87b08cc4b3cda6d844/href">https://medium.com/media/ea7afaccf1162d87b08cc4b3cda6d844/href</a></iframe><h3>4. 由 library 的製作者來提供優化</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4e237fd5762783c4512a01c77a8e04f/href">https://medium.com/media/d4e237fd5762783c4512a01c77a8e04f/href</a></iframe><p>更深刻的思考是，假設 antd Form 的 submit 是可以被 useEvent 優化，代表 Form 一定被 React.memo 包裹，那既然 Form 已經被其維護者做了第一層優化，為何不送佛送上天，直接用 withStable 優化到底，畢竟只有其維護者才知道內部是如何使用 submit 的，而 Form 的使用者根本不該管這些。</p><h3>小結</h3><p>對 1.，useEvent 是無論如何都無法優化 inline callback。<br>對 2.，問題在需要寫更多 code。<br>對 3.，問題是一不小心優化失效。<br>對 4.，心智上有負擔，要查 doc，且 component 提供者和使用者都必須知道細節。</p><h3>Closure 舊值 (outdated values) 問題</h3><p>另一個 useEvent 想要解決的是「Closure 舊值問題」。<br>RFC 給出的<a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#useeffect-shouldnt-re-fire-when-event-handlers-change">案例</a>是：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86e5c2a607833652831a42ce90170754/href">https://medium.com/media/86e5c2a607833652831a42ce90170754/href</a></iframe><p>但這個方式有幾個缺點：</p><h3>1. 需要在 effect 外定義新 function</h3><p>為了要在 effect 裡獲得最新但非依賴的值，居然一定要定義一個新 function 再去呼叫它，這讓 code 更醜了。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63528dbc7e89032842a5cc15a2a2dadf/href">https://medium.com/media/63528dbc7e89032842a5cc15a2a2dadf/href</a></iframe><h3>2. 因為 useEvent 的 callback 在 effect 之外，因此無法修改 effect 裡的值</h3><p>以下是 Dan 在推特上提供的範例：</p><h3>дэн on Twitter: &quot;To solve this, let&#39;s extract the event out of the effect! The &quot;reactive&quot; part of our code is setting up interval. What happens on tick is conceptually an event, and is not a part of the effect. We can extract onTick with useEvent. It can read latest text. Interval is set up once. pic.twitter.com/jQ6awHzxf5 / Twitter&quot;</h3><p>To solve this, let&#39;s extract the event out of the effect! The &quot;reactive&quot; part of our code is setting up interval. What happens on tick is conceptually an event, and is not a part of the effect. We can extract onTick with useEvent. It can read latest text.</p><p>讓我們新增一個count變量，然後在每次onTick增加它</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6042fcbfa850541064c177c52f8421d7/href">https://medium.com/media/6042fcbfa850541064c177c52f8421d7/href</a></iframe><h3>3. 在 useEvent 的 callback 中 await 後，依然拿不到最新值</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49bdcb6efe96bb0c77c8511b8213324f/href">https://medium.com/media/49bdcb6efe96bb0c77c8511b8213324f/href</a></iframe><p>這是很嚴重的使用陷阱，讓開發者誤以為 useEvent 包裹的 callback 裡的值都是最新的。<br>useEvent 只能保證 invoke 時值是最新的，如果 useEvent 中有 async 操作（比如 await 或 async callback），值就不一定是最新。</p><p>一定會有人跟我 argue：那就再定義一個新的用 useEvent 包住的 callback 來呼叫。<br>請看看上面這個例子，難道我要專門定義一個 onChecked callback，為的是在 await checkConnection 後 showToast？Are you kidding me?</p><h3>更好的解決方案</h3><p>試試看這個套件 <a href="https://github.com/oney/react-better-effect">react-better-effect</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e33ac3e2a2ae772f80da79498a464f5f/href">https://medium.com/media/e33ac3e2a2ae772f80da79498a464f5f/href</a></iframe><p>此方案的優點是：</p><h3>1. 不需要為了拿取最新值就定義新 callback</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/677a5bcfa0af57205b7f86e6854a17ff/href">https://medium.com/media/677a5bcfa0af57205b7f86e6854a17ff/href</a></iframe><h3>2. 可以直接在 closure 裡修改值</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0b9ef6324a67ae894852ab0155916fd/href">https://medium.com/media/c0b9ef6324a67ae894852ab0155916fd/href</a></iframe><p>closure 是為什麼 JavaScript 能時常能簡潔解決問題的關鍵，然而 useEvent 卻逼得我們不能用 closure。</p><h3>3. 任何時候都可以獲得最新值</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/608c8690295d469900ae4b9e8d34ca2a/href">https://medium.com/media/608c8690295d469900ae4b9e8d34ca2a/href</a></iframe><h3>小結</h3><p>我可以很肯定的說，用 useEvent 來解決 closure 舊值問題以獲取最新值，應該被視為 anti-pattern，讓 code 更髒、又容易寫出有 bug 的程式。</p><h3>總結</h3><p>useEvent 無法解決所有 closure callback 所造成的問題。</p><p>為了達成 useEvent 提供的優化，需要修改大量現有的 code，例如用 useEvent 包住現有 callback、需要把 inline callback 提出來。然而 useEvent 優化卻不全面，還讓 code 更無序了。</p><p>我認為上面所提供的 <a href="https://github.com/oney/react-with-stable">react-with-stable</a> 和 <a href="https://github.com/oney/react-better-effect">react-better-effect</a> 套件應該是更優雅、更全面的解決方案，希望能被 React 官方採用。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de7fc2e509e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why useEvent is not good enough (and here is a better solution)]]></title>
            <link>https://levelup.gitconnected.com/why-useevent-is-bad-and-here-is-a-better-solution-c61ee507a82e?source=rss-78cc115efee------2</link>
            <guid isPermaLink="false">https://medium.com/p/c61ee507a82e</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Howard]]></dc:creator>
            <pubDate>Wed, 01 Jun 2022 03:11:42 GMT</pubDate>
            <atom:updated>2022-06-05T11:25:31.782Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I worked at Facebook as Software Engineer and created <a href="https://github.com/react-native-webrtc/react-native-webrtc">react-native-webrtc</a> repo having ~4000 stars.</blockquote><p>This article will convince you that <a href="https://github.com/reactjs/rfcs/pull/220">useEvent RFC</a> is not a perfect solution to the issues of callbacks in functional components. I will explain the shortcomings and pitfalls of useEvent, and provide better solutions.</p><h3>useEvent RFC</h3><p><a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md">Here is the link of the RFC</a>.<br>Strongly recommend to read the RFC before reading this article.</p><p>In the RFC, useEvent aims to solve 2 issues:</p><ol><li>Provide <strong>stable identity callbacks</strong>, so the components getting props of event callbacks won’t re-render.</li><li>Get <strong>fresh values in callbacks </strong><em>asynchronously</em>. Solve the problem of capturing outdated values in closures.</li></ol><p>However, useEvent doesn’t solve these 2 issues well.</p><h3>Stable identity callback</h3><p>useEvent can provide stable identity callbacks.<br><a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#basic-example">The useEvent RFC’s example</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d06034adecfced1d02621be239e076ff/href">https://medium.com/media/d06034adecfced1d02621be239e076ff/href</a></iframe><h3>Better solution</h3><p>Try this package <a href="https://github.com/oney/react-with-stable">react-with-stable</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/125d606316c79e97d1e3492b030aee04/href">https://medium.com/media/125d606316c79e97d1e3492b030aee04/href</a></iframe><p>Wrap SendButton with <strong>withStable</strong> HOC and explicitly declare <strong>onClick</strong> as a stable prop. That’s it! These are all the code you have to add.<br><strong>No need to wrap event callbacks</strong>!!!!!!!!!!</p><p>Remember even if you use useEvent, you still have to use React.memo to wrap the components to eliminate unnecessary re-renders.</p><p>Let’s compare:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba6d87be75e534c72bf337711a4f8cbc/href">https://medium.com/media/ba6d87be75e534c72bf337711a4f8cbc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*K9-xcLt2VfDTgFlMS60Akw.png" /></figure><p>The shortcomings of useEvent and advantages of withStable are:</p><h4>🔴 1. [useEvent] Can’t wrap inline callbacks</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/853ecc2da7fca154f7a4663bc5fb9ad5/href">https://medium.com/media/853ecc2da7fca154f7a4663bc5fb9ad5/href</a></iframe><p>It’s very common to render a list of components in a loop. And we leverage the benefit of closure to pass the item in the callback. However, it’s impossible to use useEvent here because any hook can’t be used in <strong>loops</strong> and <strong>conditions</strong>.</p><h4>✅ 1. [withStable] Work for inline callbacks (e.g. loops)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cb052c500d542a921ef41235abe0aa7/href">https://medium.com/media/6cb052c500d542a921ef41235abe0aa7/href</a></iframe><h4>🔴 2. [useEvent] Need to useEvent every time and easy to forget</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/083cb526c89907a2491bdb8be9608ee2/href">https://medium.com/media/083cb526c89907a2491bdb8be9608ee2/href</a></iframe><p>Like useCallback, in order to optimize, we have to wrap with useEvent every time. This is stated in <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#drawbacks">Drawbacks</a> section of the RFC:</p><blockquote>Compared to a plain event handler, wrapping with useEvent looks more noisy.</blockquote><p>In fact, the computing and memory cost of useEvent is cheap. The real cost of it is the cost of development (i.e. <a href="https://medium.com/swlh/what-is-dx-developer-experience-401a0e44a9d9">DX</a>) which requires developers to remember and write code.</p><h4>✅ 2. [withStable] Wrap once, optimize anywhere</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3e64231318f90ea00284e8ff5fb031/href">https://medium.com/media/0d3e64231318f90ea00284e8ff5fb031/href</a></iframe><p>Say after useEvent releases, you have a child component to optimize and there are 10 parent components using it, you have to refactor to write useEvent 10 times!</p><p>Comparatively, you only have to wrap the child component with withStable once, and all the parent components get optimization.</p><p>That is what we call <a href="https://medium.com/swlh/what-is-dx-developer-experience-401a0e44a9d9">DX</a>.</p><h4>🔴 3. [useEvent] Doesn’t help on conditional values</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52e0d77bc692bce3ac6586fe5e29e156/href">https://medium.com/media/52e0d77bc692bce3ac6586fe5e29e156/href</a></iframe><p>Say onOdd and onEven is stable, but the condition text.length % 2 changes frequently, so SendButton can’t get the same identity callback that causes re-render. This is stated in <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#drawbacks">Drawbacks</a> section of the RFC:</p><blockquote>The “conditional event” case like onSomething={cond ? handler1 : handler2}</blockquote><p>To fix this, we have to define a new callback wrapped by useEvent which is unpleasant.</p><h4>✅ 3. [withStable] Work for conditional values too</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb81430ca829fb3e086cb28a9c9e3b26/href">https://medium.com/media/bb81430ca829fb3e086cb28a9c9e3b26/href</a></iframe><h4>🔴 4. [useEvent] Burden on library users</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/608bb6cf8a5a659fed1b6d7ba845dd2e/href">https://medium.com/media/608bb6cf8a5a659fed1b6d7ba845dd2e/href</a></iframe><p>Library users need to know which callback props are useEvent-safe (only used in event handler, not in renders).<br>If useEvent-wrapped submit is used in renders, <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#functions-called-during-render-still-use-usecallback">React will throw</a>.</p><h4>✅ 4. [withStable] Library makers do the performance optimization</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a3777ee5155baa9a903130a6122b9fb/href">https://medium.com/media/6a3777ee5155baa9a903130a6122b9fb/href</a></iframe><h4>Brief</h4><ol><li>useEvent can’t work for inline callbacks like in loops and conditions.</li><li>Why not wrap once, optimize anywhere?</li><li>Let component maintainers optimize, and component users get it free.</li></ol><h4>Bonus</h4><p>withStable will also help on ignoring stable callbacks in the dependency list. <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#linter-plugin">This issue</a> is stated in the RFC:</p><blockquote>The useEvent functions passed from parent components would have to be declared as dependencies.</blockquote><p>The linter can figure out what props are stable by checking withStable([&quot;onClick&quot;], so the naming convention of handle* or on* is not necessary.<br>And the linter can also check if a stable prop is passed to a non-stable prop of a child component.</p><h3>Get fresh values in callbacks</h3><p>useEvent RFC also wants to solve <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#useeffect-shouldnt-re-fire-when-event-handlers-change">outdated values in closure</a> issue like this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74cb6711a73f878ccdbbf1b462ef652a/href">https://medium.com/media/74cb6711a73f878ccdbbf1b462ef652a/href</a></iframe><p>One thing to note is, the values in callbacks might be outdated only when the callings are not all synchronous, such as after await or the callback is invoked asynchronously<em>.</em></p><p>The pattern of useEvent to get fresh values has some pitfalls and disadvantages:</p><h4>1. Need to define new callbacks outside of effects</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d691a7216647b79e88becbdf06bf14aa/href">https://medium.com/media/d691a7216647b79e88becbdf06bf14aa/href</a></iframe><h4>2. Can’t access values inside of effects</h4><p>Take <a href="https://twitter.com/dan_abramov/status/1522227655940218882">this Dan’s tweet</a> as example</p><h3>дэн on Twitter: &quot;To solve this, let&#39;s extract the event out of the effect! The &quot;reactive&quot; part of our code is setting up interval. What happens on tick is conceptually an event, and is not a part of the effect. We can extract onTick with useEvent. It can read latest text. Interval is set up once. pic.twitter.com/jQ6awHzxf5 / Twitter&quot;</h3><p>To solve this, let&#39;s extract the event out of the effect! The &quot;reactive&quot; part of our code is setting up interval. What happens on tick is conceptually an event, and is not a part of the effect. We can extract onTick with useEvent. It can read latest text.</p><p>Say we define a new variable count and want to increase it in every tick.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fbf5d26e94c96bcc56fb2c0bc030eb1/href">https://medium.com/media/7fbf5d26e94c96bcc56fb2c0bc030eb1/href</a></iframe><p>This means if we want to use useEvent, we need to give up the benefit of JavaScript closure anymore! useEvent forces us to jump out of current closure to a component-level callback that is wrapped by useEvent.</p><h4>3. Can’t still get the fresh values always</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dbfbdaac865c937233915166cd68442/href">https://medium.com/media/7dbfbdaac865c937233915166cd68442/href</a></iframe><p>This is a very serious pitfall. It’s too easy to be unaware that some values aren’t fresh anymore after await or async callbacks.<br>This is stated in <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#drawbacks">Drawbacks</a> section of the RFC:</p><blockquote>you don’t get truly “live” bindings.</blockquote><p>Defining a new callback onChecked looks worse for me.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16f1599f26ad6a79ca36f13e479d97dc/href">https://medium.com/media/16f1599f26ad6a79ca36f13e479d97dc/href</a></iframe><p>I don’t like the above code personally. It loses the point to use async/await syntax.</p><h3>Better solution</h3><p>Try this package <a href="https://github.com/oney/react-better-effect">react-better-effect</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01720805077d0fe678f7e8d985ad5cde/href">https://medium.com/media/01720805077d0fe678f7e8d985ad5cde/href</a></iframe><p>Inject {theme} to useEffect of react-better-effect, and then get theme by $.theme in the effect.</p><p>The advantages:</p><h4>1. No need to define new callbacks outside of effects</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97a6477e4cffe52d58968ac8e41271f0/href">https://medium.com/media/97a6477e4cffe52d58968ac8e41271f0/href</a></iframe><h4>2. Can access values by staying in the current closure</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e7f06e7501af85906f57d0c85ab4812/href">https://medium.com/media/9e7f06e7501af85906f57d0c85ab4812/href</a></iframe><h4>3. Always get the fresh values asynchronously</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b4e6cc5da32ade861a7b650e2a59a6a/href">https://medium.com/media/9b4e6cc5da32ade861a7b650e2a59a6a/href</a></iframe><p>Never worry about the values are outdated.</p><h4>Brief</h4><p>In my opinion, using useEvent to ensure fresh values is a little bit <strong>anti-pattern</strong> that will cause too many problems.</p><h3>Summary</h3><p>useEvent can solve partial issues of callbacks in React, but still leaves some issues unsolved and causes pitfalls. I can imagine that useEvent will result in a lot of unnecessary refactoring such as moving event handler closures and effect closure to component level for useEvent. It makes code more ugly but still can’t fix all the issues of callbacks.</p><p>withStable HOC can really solve the “<a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#drawbacks">should I use </a><a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#drawbacks">useCallback everywhere?</a>&quot; confusion. In my most rough estimate, 90% callbacks in React apps are event callbacks. If using withStable, we can reduce the usage of useEvent and even useCallback by 90%.</p><p>And even when <a href="https://www.youtube.com/watch?v=lGEMwh32soc">React Forget</a> is out and it auto wraps callbacks, but it is still <strong>unable to distinguish</strong> callbacks between render callbacks or event callbacks. That means developers have to <strong>explicitly annotate</strong> a callback as for render or event.</p><p>I personally recommend that React core should include withStable<em> </em>HOC (merge to React.memo) from <a href="https://github.com/oney/react-with-stable">react-with-stable</a> and the better useEffect from <a href="https://github.com/oney/react-better-effect">react-better-effect</a>. They solve the callback issues more elegantly and more powerfully.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Appendix</h3><p>The core idea of <a href="https://github.com/oney/react-with-stable">react-with-stable</a> and <a href="https://github.com/oney/react-better-effect">react-better-effect</a> is:<br>Let callback <strong>users/consumers/usage sites</strong> decide how they want to use the callback.</p><p>This idea is kind of also <a href="https://github.com/reactjs/rfcs/blob/useevent/text/0000-useevent.md#wrapping-events-at-the-usage-site">presented in the RFC</a>: Wrapping events at the usage site, but useEvent can only do it for useEffect, can’t when passing callback props to components.</p><p>For example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f8cfabdaf5c8596bc96dff54d5a3b2c/href">https://medium.com/media/1f8cfabdaf5c8596bc96dff54d5a3b2c/href</a></iframe><p>For useSyncTitle, format should be in deps of the effect.<br>For useShowRating, format should NOT in deps of the effect.<br>For Movie, format should NOT be a stable callback.<br>For Like, format can be a stable callback.</p><p>Using <a href="https://github.com/oney/react-with-stable">react-with-stable</a> and <a href="https://github.com/oney/react-better-effect">react-better-effect</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/031ae2b08f25a79ec0ee9b1e3ebdd5d5/href">https://medium.com/media/031ae2b08f25a79ec0ee9b1e3ebdd5d5/href</a></iframe><h3>Always wrapping callbacks</h3><p>I support always wrapping a callback with useCallback no matter it is an event handler or derived callback for render or deps of effect.</p><p>useCallback is a shortcut of useMemo. <a href="https://reactjs.org/docs/hooks-reference.html#usememo">The doc</a> describes useMemo as:</p><blockquote>This optimization helps to avoid expensive calculations on every render.</blockquote><p>But useMemo is not just for avoiding calculating expensive values, also for memoizing the same <strong>non-primitive</strong> values(i.e. JavaScript object and function) to avoid <strong>unnecessary re-rendering and effect re-triggering</strong>.</p><p>That’s because if we don’t useMemo or useCallback for object or function, even though there is actually no difference between old and new values, they are considered as different when comparing (i.e. Object.is or ===).</p><h3>Categorize callbacks</h3><p>Don’t categorize callbacks into event handlers or non event handlers.</p><p>Categorize callbacks into reactive or unreactive.</p><h4>For a component accepting a callback prop:</h4><ol><li>If the callback is used in <strong>render</strong>, the component wants it to be <strong>reactive</strong>.</li><li>If it’s used in <strong>event handler</strong>, the component wants it to be <strong>unreactive</strong>.</li></ol><h4>For useEffect:</h4><ol><li>If the callback should trigger the effect, it should be <strong>reactive</strong>.</li><li>If not, it should be <strong>unreactive</strong>. (Getting fresh values asynchronously is a separate problem to solve)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c61ee507a82e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/why-useevent-is-bad-and-here-is-a-better-solution-c61ee507a82e">Why useEvent is not good enough (and here is a better solution)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>