<?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 Guopeng Liang on Medium]]></title>
        <description><![CDATA[Stories by Guopeng Liang on Medium]]></description>
        <link>https://medium.com/@guopengliang?source=rss-4331f3041850------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xOYZjPsSFN6YjEmo.png</url>
            <title>Stories by Guopeng Liang on Medium</title>
            <link>https://medium.com/@guopengliang?source=rss-4331f3041850------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:46:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guopengliang/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[Understanding React Hooks from the perspective of Render Versioning]]></title>
            <link>https://medium.com/@guopengliang/understanding-react-hooks-from-the-perspective-of-render-versioning-af773e091d40?source=rss-4331f3041850------2</link>
            <guid isPermaLink="false">https://medium.com/p/af773e091d40</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Guopeng Liang]]></dc:creator>
            <pubDate>Sun, 26 May 2019 16:34:40 GMT</pubDate>
            <atom:updated>2019-06-22T11:36:59.708Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqacoHV6MwnBhGNs3GBx8g.png" /></figure><p>React Hooks has been officially released in React v16.8.0 earlier this year and it’s getting more and more adoption across the world over the past few months. Basically, it is a new way to write functional components that are as powerful as, or even more powerful than, Class-based components. It not only enable us to write codes that are easier to organize and understand, but also allow us to gain potential performance improvements with the upcoming React Concurrent mode.</p><p>As an experienced React developer, I find it quite challenging to change my mindset from Class-based to Hooks-powered components in the beginning. It took me many hours and dozens of trials and experimentations just to grasp a basic understanding. Especially when I was heavily influenced by what the “old-school” Class-based components offer: life-cycle events, Class instance properties for storing data and imperative methods, etc.</p><p>Having spent the past few months refactoring my app <a href="https://dailycost.com/">DailyCost</a> from Class-based components to Hooks-powered functional components, and writing my own custom hooks, I have developed my own understanding of React Hooks, and I like to share it with you from the perspective of Render Versioning.</p><p>Yes, like version control! 😆</p><h3>The basics of Render Versioning</h3><p>In React, we know that a functional component is a simple function that takes some props and returns something for React to render. Functional component used to be “pure” (as formerly the best practice to do so). Namely, given the same props, it should always return the same result. However, it’s not pure anymore with Hooks. Hooks provides many tools for us to write “impure” functional components.</p><p>Props, state (useState and useReducer) and context (useContext) are the primary factors that account for render versioning. A change to one of these values, or to multiple of them at the same time, will trigger the component’s re-render. In addition to these primary factors, refs (useRef), callbacks (useCallback), imperative handles (useImperativeHandle) and side-effects (useLayoutEffect and useEffect) are also important factors you need to get the final render result, which in whole contributes to the render versioning. I’ll explain this later in this article.</p><p>To understand it, let’s begin with this Button component below. The initial render is <strong>Version 0</strong> (count = 0). When we click the button, the component’s internal state count is changed, triggering the component to re-render, so we get <strong>Version 1</strong> (count = 1). Click again, and we get <strong>Version 2</strong> (count = 2).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4033de2f6b8766027d84ea3dc7ef5b40/href">https://medium.com/media/4033de2f6b8766027d84ea3dc7ef5b40/href</a></iframe><p>Under the hood, the reference to the Button functional component does not change on each render. But, the function itself is somewhat “mutated” as its internal state has changed. Thus, we expect the return of the function is different from its previous return. <em>(Edit: thanks to </em><a href="https://medium.com/u/a3a8af6addc1"><em>Dan Abramov</em></a><em> for pointing out that “mutated” is not a precise or even correct term to describe such behavior. As from the perspective of “React being a bit of its own language bolted on top of host language (JS)”, it would be better to think of it as React-pure.)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQ0Q4XOznifnlTFfNeiXNA.png" /></figure><p>Now, what if the Button component’s parent component Page is updated and re-rendered, causing Button to re-render? Good question! In this case, we are still left with <strong>Version 2</strong> (count = 2). Because its internal state count hasn’t changed, and count is the only factor that accounts for the render versioning of Button component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ag2TDawWn45IRLmT_1UTtw.png" /></figure><blockquote>If non of the versioning factors is changed, a Hooks-powered component should remain the same version and always return the same result.</blockquote><p>This is a very important notion when writing such components, as it help us avoid unwanted side-effects which cause problems that are hard to identify as the code base gets bigger. In fact, it also compliments the upcoming Concurrent Mode, with which the same component might be re-rendered multiple times regardless of props/state/context change in order to optimize performance. (Further: you could use <a href="https://reactjs.org/docs/strict-mode.html">&lt;React.StrictMode&gt;</a> to test this behavior and prepare for it.)</p><p>Nevertheless, this Button component is just a simplified example to illustrate the basic factors of Render Versioning. In real world scenarios, components are much more complicated, we should be careful to take all the versioning factors as mentioned above into consideration.</p><h4>Primary versioning factors</h4><p>Any update (previous !== current) to one or more of the following factors will trigger re-render and change the component’s Render Version.</p><ul><li><strong>props</strong>: passed down from parent component or HOC</li><li><strong>state</strong>: useState and useReducer hooks</li><li><strong>context</strong>: useContext hook</li></ul><h4>Additional versioning factors</h4><p>These versioning factors are somewhat different from the primary ones above. Because the hook functions to declare these values provide an extra dependencies param to bail out reference change. We can utilize it to ensure these factors remain the same reference (previous === current) upon re-render. However, be cautious for advanced usages, such as reading/updating state from callbacks. Make sure the callback function and the value it reads are on the same Render Version, avoid any stale access.</p><ul><li><strong>refs</strong>: useRef hook (a ref is a mutable object exposing ref.current)</li><li><strong>callbacks</strong>: useCallback hook</li><li><strong>imperative handles</strong>: useImperativeHandle hook</li><li><strong>side-effects</strong>: useLayoutEffect and useEffect hooks</li></ul><h3>Exploring the weird things using the Render Versioning mindset</h3><p>As we adopt the mindset of Render Versioning, many seemingly weird Hooks behaviors could be explained and understood in a simple and elegant way.</p><ul><li>Implementing “life-cycle events” with hooks</li><li>Accessing often-changing state and props from event handlers</li><li>Side-Effects targeting specific render version</li><li>State update within the same render loop</li></ul><p>To further explore these topics, I’ll write another article in the near future.</p><h3>Conclusion</h3><p>Refactoring codes from Class-based to Hooks-powered require lots of effort. The Rendering Version mindset is based on my many experiments and failed attempts, and summarized from such experience of refactoring a fairly large code base. It helped me a lot. And I hope it would benefit you too.</p><p>If anything in this article is not clear, or do you have any questions, thoughts, suggestions or corrections to point out, please feel free to leave a comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af773e091d40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[为什么梦是黑白的？]]></title>
            <link>https://medium.com/@guopengliang/why-dreams-are-black-and-white-fd4f1bcbb04?source=rss-4331f3041850------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4f1bcbb04</guid>
            <category><![CDATA[dreams]]></category>
            <category><![CDATA[fiction]]></category>
            <dc:creator><![CDATA[Guopeng Liang]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 03:47:15 GMT</pubDate>
            <atom:updated>2019-03-19T03:47:15.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LLql_jx-e9mhcAOG" /><figcaption>Photo by <a href="https://unsplash.com/@ty_dudley?utm_source=medium&amp;utm_medium=referral">Tyson Dudley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>这个世界我们叫做地球，太阳是离我们地球最近的一颗恒星。在我们生活的这个世界里，无论是白天还是黑夜，我们所能看到的一切物质主要是由太阳光照亮的。我们之所以能看见色彩，是因为太阳辐射波包含了“红橙黄绿蓝靛紫”的可见光谱（Visual Spectrum），波长大约在 400nm ～ 760nm。太阳辐射波照射到不同的物质表面，经过反射后进入眼球被视网膜接收，再经过大脑处理，最终由我们的意识认知道不同的色彩。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apWtPTVjvls-WoHKULJC4Q.png" /><figcaption>可见光谱只占由宽广的电磁波谱的一小部分 （图片来源：<a href="https://zh.wikipedia.org/wiki/%E5%8F%AF%E8%A7%81%E5%85%89">Wikipedia</a>）</figcaption></figure><p>在做梦的时候，人的灵魂脱离躯体，离开了这个世界，进入了另一个世界。醒来后，我们能依稀回忆起梦里的所见所闻，但又很快的忘却。很少有人能记住完整的梦，但绝大部分人所会想起的梦都是黑白的。</p><p>为什么梦是黑白的而不是彩色的？梦的世界并不是由太阳照亮的，而是某种特殊的“光源”所照亮。这种“光源”非常的特殊，它并不包含可见光谱的部分。我们看不见色彩，但仍然能够感知到明暗黑白，这类似于红外夜视仪的原理。红外夜视仪能够发射和接收红外辐射，这些肉眼看不见的辐射波照射到物体表面后，经过反射再被夜视仪接收，经过处理形成肉眼可见的黑白图像。</p><p>梦世界的这种特殊“光源”从何而来，我们不得而知。或许这才是我们真实存在的世界，一个经过精心设计和制造出来的世界。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4f1bcbb04" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>