<?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 Kush Tran on Medium]]></title>
        <description><![CDATA[Stories by Kush Tran on Medium]]></description>
        <link>https://medium.com/@kushtran?source=rss-c853f5a06ee4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9uIALCUC6VwAIdgqdMnrsA.jpeg</url>
            <title>Stories by Kush Tran on Medium</title>
            <link>https://medium.com/@kushtran?source=rss-c853f5a06ee4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 01:56:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kushtran/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[Simple hack with React Element and JSX]]></title>
            <link>https://javascript.plainenglish.io/why-react-elements-position-matters-1e50aa239560?source=rss-c853f5a06ee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e50aa239560</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kush Tran]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 13:03:10 GMT</pubDate>
            <atom:updated>2022-01-06T16:34:57.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zi6_XtN2o_ZxuH6lcTIhbg.png" /></figure><p>There is no perfect software. As developers, we always have to be aware of future changes. Understanding that pain, React has a powerful composition model, which is easy to swap over components. Since we can creatively choose how to locate and swap our components, there are different results, each having its own benefit, depending on context. For the best, in this article, we are going to discuss different ways to locate our component, get to understand them, and wisely choose which is appropriate.</p><h3>Table of Contents:</h3><ul><li><strong>What is React Element? JSX transpilation?: </strong>Why? Later we will explain the next concepts based on this.</li><li><strong>The Rendering Behavior:</strong> The role of React element in the rendering process, how wasted renders happen?</li><li><strong>How constant Elements help optimize renders</strong></li></ul><h3><strong>What is React Element? JSX transpilation?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*yKEMbP5qB7Yug_9t9smbZQ.jpeg" /></figure><p>A <strong>React Element</strong> is what gets returned by a <strong>component</strong>. It’s an object that virtually describes the tree node that the component represents.</p><p>Wait, what? I don’t see any object returned by components? Isn’t it <strong>JSX</strong>?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9e08e41cc5d442a24f6b4948a5572b/href">https://medium.com/media/0b9e08e41cc5d442a24f6b4948a5572b/href</a></iframe><p>Let me explain!</p><p>It’s true that Component returns JSX, but JSX is a special syntax which JavaScript can’t read directly. Instead, it requires transpilers to turn it into <strong>createElement</strong> calls, which are just JavaScript plain objects. Depending on your stack, the transpilation can be done either by <strong>Babel</strong> or <strong>TypeScript</strong>. That’s why you always have to import React from ‘react’ to write JSX, because it needs to run<strong> </strong>React.createElement , so React needs to be in scope. Since React 17, there is a new JSX Transform — there’s no requirement for that import anymore, in case you’re curious, read more <a href="https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html">here</a>.</p><p>If you want to test out how some specific JSX is converted into JavaScript, you can try out <a href="https://babeljs.io/repl">Babel online compiler</a>.</p><h4>Multiple Children</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b37049dfb16ae707d5bd51a38de9a0e/href">https://medium.com/media/6b37049dfb16ae707d5bd51a38de9a0e/href</a></iframe><p>React doesn&#39;t limit the number of children of one component, it is then compiled to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb50d8922eebe88f89d7381d17e2d0e7/href">https://medium.com/media/fb50d8922eebe88f89d7381d17e2d0e7/href</a></iframe><p>At this point, we learn pretty the idea of JSX and Element, this will support what’s upcoming.</p><h3><strong>The Rendering Behavior:</strong></h3><p>Rendering is a process when React finds out how the layout tree should be, it happens when mounting and updating. During the update, Reconciliation is executed to collect the difference between the new tree and the old tree, once a component is marked needing update, React re-renders all of its children, even those child components stay unchanged. In this regard, wasted renders appear and might cost much effort, possibly slowing our app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FolTohP6HnYjwAodCLz%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FolTohP6HnYjwAodCLz&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2FolTohP6HnYjwAodCLz%2Fgiphy.gif%3Fcid%3D790b76114014ee48f614551c900b970464a0570a602bc47d%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="583" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d44e36b41f6dc2e6525ea5779084e3c/href">https://medium.com/media/3d44e36b41f6dc2e6525ea5779084e3c/href</a></iframe><p>In the GIF, I built an example, where Component A &gt; Component B &gt; Component C &gt; Component D, A is the parent component of B, and so on. Due to the behavior of rendering in React, when component A is marked as needing re-render, all of the children re-render too, it doesn’t care if the children are not changed. It starts tracking from the parent node and diff into its children, so re-rendering B only triggers C &amp; D, A is out of it.</p><p>Sometimes, one of the children is slow, and we don’t want unnecessary re-renders on slow components. There are two ways to optimize something, either make it run faster or skip the work. In React, most of the optimization is about skipping work. React provides 3 main methods to achieve this: <strong>React.PureComponent</strong>, <strong>shouldComponentUpdate</strong>, <strong>React.memo</strong>. I won’t go into details of it, you can see it in <a href="https://javascript.plainenglish.io/react-native-why-props-references-break-optimizations-79c463ca0723">my previous blog</a>. Instead, leveraging the understanding of Element and JSX, we got another simple hack, without using the above 3 methods.</p><h3><strong>How constant Elements help optimize renders</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f5686100de688e4a4e8a3bab2de18a4/href">https://medium.com/media/7f5686100de688e4a4e8a3bab2de18a4/href</a></iframe><p>Looking at this example, we have a SlowComponent which is delaying the rendering for <strong>1 second</strong>, and a TestCon displays count, it increases the count upon a press.</p><p>Let’s see the difference between the 2 cases, with SlowComponent and without SlowComponent:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl1BmVlw7KHpT97P8XC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fl1BmVlw7KHpT97P8XC&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fl1BmVlw7KHpT97P8XC%2Fgiphy.gif%3Fcid%3D790b7611fe007e79fc939fbdb7c9f2b5b9ebe3823d7ffa64%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="282" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd075ce8e3fa105fc55fc0abff3cfe7/href">https://medium.com/media/dfd075ce8e3fa105fc55fc0abff3cfe7/href</a></iframe><p>As we can see, when I comment out the SlowComponent, our counter example runs smoothly; otherwise, with SlowComponent, it delays the render of SlowComponent for <strong>1 second</strong>, and that affects TestCon too. Why? As I explain, the rendering behavior above, setCount inside TestCon triggers its children to re-render too, SlowComponent delays 1 second, and TestCon as parent component has to wait for SlowComponent to complete to eventually commit to the tree.</p><h4>The Fix</h4><p>The common fixes are <strong>Colocate State</strong>, and the 3 methods I mentioned above. <strong>Colocate State</strong> means wrapping count state and Component using it into a separate component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba5b41f7534c2579fb25f7e9bdddf702/href">https://medium.com/media/ba5b41f7534c2579fb25f7e9bdddf702/href</a></iframe><p>WrapperComponent is a newly added component, wrapping count state and layout using it. Doing this prevents SlowComponent to be re-rendered, because now the update is marked at WrapperComponent, not TestCon anymore, so it only looks to WrapperComponent and its children.</p><p>Wait! If there were another MondayComponent needs to use count, or a new ParentView needs it too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bf6cdc8e4988ca7dd910573bf66664b/href">https://medium.com/media/1bf6cdc8e4988ca7dd910573bf66664b/href</a></iframe><p>Oh no! We can’t use colocate state in this situation, we need count at TestCon to pass it to ParentView and MondayComponent too.</p><p>A simple trick will lift SlowComponent up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed658e0a9b616c752f0983560cd1440f/href">https://medium.com/media/ed658e0a9b616c752f0983560cd1440f/href</a></iframe><p>Lift content up means pass SlowComponent to TestCon as prop, children is just a prop, so props.children or props.renderSlow or whatever name you like is not matter. How does doing this prevent SlowComponent from re-rendering?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af964f58b7b6afcc712a6883df9c1bf9/href">https://medium.com/media/af964f58b7b6afcc712a6883df9c1bf9/href</a></iframe><p>I simplified the example a bit for a better look, so only View and SlowComponent now.</p><p>We use what we learn above about <strong>JSX</strong> and <strong>createElement</strong> to describe 2 ways of writing.</p><p>For the 1st case, React.createElement(SlowComponent) is called every time TestCon re-render, so it is always referentially different between renders, so React just re-render it, this explains why other children components get re-rendered too.</p><p>For the 2nd case, regardless of how many time TestCon re-renders, props.children is always the same, because based on the place it’s defined, it’s a constant, and its reference is the same.</p><p>Reference plays an important role inside the React ecosystem, it affects most optimization approaches, because React internally uses shallow compare.</p><p>So lift up content prevents re-rendering the content. Be careful, in real-world examples, there are cases when you want to re-render children along with the parent or skip re-rendering children for a performance boost — it depends. So choose wisely:</p><pre>&lt;TestCon&gt;&lt;SlowComponent/&gt;&lt;/TestCon&gt; and use props.children<br>==&gt; when you want skip SlowComponent rendering</pre><pre>otherwise, use SlowComponent directly for re-render along with parent</pre><pre>const TestCon = ()=&gt;{<br> return(<br>   &lt;View&gt;<br>    &lt;SlowComponent/&gt;<br>   &lt;/View&gt;<br> )<br>}</pre><p>Overall, this is one simple hack among many approaches to optimize our components, just by placing them around. Use it appropriately, different situations need different approaches.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter</em></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><em>community Discord</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e50aa239560" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-react-elements-position-matters-1e50aa239560">Simple hack with React Element and JSX</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Derived State in React]]></title>
            <link>https://javascript.plainenglish.io/understanding-derived-state-in-react-1491a9ee3a6b?source=rss-c853f5a06ee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1491a9ee3a6b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kush Tran]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 10:23:41 GMT</pubDate>
            <atom:updated>2022-01-03T06:25:28.325Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about the hidden risks and how we can benefit from understanding them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*OtNwFVjXn-2EalYVchdlbw.jpeg" /></figure><p>The <em>Prop</em> concept plays an important role in forming our awesome framework - React. It is one of the main methods of communication between components, bypassing it down, strengthens the relationship between parent and child components. Not only used to describe components, it sometimes seeds data to form <em>initial State</em>, another wonderful usage, yet controversial because there are hidden risks, this article aims to point them out and let’s see how we can benefit from understanding them.</p><h3>Table of Contents:</h3><ul><li><strong>What is a Derived State? Why do we need it?</strong></li><li><strong>Two sources of truth:</strong> what problem it brings, and solution?</li><li><strong>Accidentally mutate props:</strong> unpredictable bugs</li><li><strong>Summary</strong></li></ul><h3><strong>What is a Derived State? Why do we need it?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*5yNesmiO81Qptb_Gz_w0Zg.png" /></figure><p>When a prop is used to initiate a state, that state is called a <strong>derived state</strong>. We can see the prop as a data dependency, which the state uses to form its default value. Like my SetContainer the component has a state named sets and I use props.sets to initial sets.</p><p>Why we don’t use props.sets it directly? Why do we have to map it to another variable (sets state) to use?</p><p>Great question! Short answer: temporary mutation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIDV8Xs7fcShKPIJM3p%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FIDV8Xs7fcShKPIJM3p%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FIDV8Xs7fcShKPIJM3p%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="538" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19f04adc39229d78c0b5e3b6f3a1e32/href">https://medium.com/media/b19f04adc39229d78c0b5e3b6f3a1e32/href</a></iframe><p>Imagine we have a list, let’s say a list of fitness exercises, each exercise has its own detail, like many sets with each set containing different duration, tempo, rest time. And users can pick an exercise and choose to edit the detail, after their edit, the exercise detail has to go back to its original sets detail. So the whole process is definitely like a temporary mutation on sets. We mutate the sets and render it out, once we did, we put it back. We need SetContainer to get the original sets, and only change the sets inside their scope, without affecting the original sets. The original sets here is props.sets, and the sets we gonna mutate is sets. Doing this way, we ensure the ability to change by setting state and it won’t affect the original sets. In the example gif, I edited a value from 15 to 20, and when I got out of edit mode, it’s back to 15, don’t mind the language in the app lol.</p><p>As you can see, even <strong>Derived State</strong> is called anti-pattern, sometimes we need it. Personally, I think an anti-pattern is not bad at all, it is not perfect, it contains hidden risks, but if we are aware of those risks, it’s still a good approach anyway! My article is not about criticizing <strong>Derived State</strong>, but about understanding the risks and conquering them!</p><h3>Two Source of Truth</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*sO-QzThr7A_gJnPCHsPMYw.jpeg" /><figcaption>Who doesn’t love Conan?</figcaption></figure><p>Shout out for Conan lol 💁</p><p>As we learn React, we must have come across the <strong>Single source of truth </strong>somewhere, like in Redux principle, or seeing other developers discuss it on Twitter, even many blog posts mention it.</p><p>For me,<strong> a Single source of truth</strong> is often misunderstood, it doesn’t mean all things come from the same place, it means for every particular piece of data, there is one particular place where it comes from. This makes easy tracking of data flow, easing the frustration of programming.</p><p>By deriving state from props, you split the source of truth for one thing into two. It was originally a single thing (prop), derived state lets it diverge and potentially get out of sync, leading to problems like the below issue I found on StackOverflow.</p><p><a href="https://stackoverflow.com/questions/54865764/react-usestate-does-not-reload-state-from-props">React.useState does not reload state from props</a></p><p>Briefly explain the issue, he uses a prop to the initial state, and when the prop changes, he expects the state would update like how it’s derived from the prop, but it doesn’t. His code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-7ZtiiKh0ko2W9rekJdMw.png" /></figure><p>Inside the function component, almost everything inside the function re-runs every it called (re-render), it’s the function behavior of javascript. The useState the hook is a bit special because its creation isn’t re-executed, much like setting state in the constructor for a class component. This leads to the issue above, “useState does not reload state from props”.</p><p>Writing this way, his component is likely to lose the future update from props.user, his data flow is now split into 2 sources, and as we see here, they are out of sync.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*dLWu7S5zd5BiTzlTQjVKSg.gif" /></figure><p>In the issue thread, others give him the solution of useEffect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-RETcz9YTvywrfqP-G2Zg.png" /></figure><p>This works, unlike useState, useEffect re-executed after every render, as long as it meets the conditional dependency in the second argument. Now he has a way to sync his prop and state, every time his props.user updated, he sets a new value for his user state, but another problem appears, let me show you.</p><p>Like I mention about the temporary mutation above, this Avatar component doesn&#39;t need a derived state if its only purpose is to display the avatar. It gotta be something like editing avatar, for making more sense.</p><p>Saying we are doing the editing avatar feature, we let the user choose their profile picture as many times as they want, we don’t wanna update props.user data or send update requests to the server immediately, it wastes. We want to make the actual update on the final decision of the user like he chooses his profile 5 times and on the 5th chosen, we send the update request to our server and locally update props.user. In my opinion, I just need, don’t need the whole props.user data, but anyway I just stick to the StackOverflow issue above.</p><p>While choosing/editing the avatar, props.user suddenly changed, and useEffect syncs user state and props.user. By setting a new state, we lost our temporary mutation, our editing. We gotta fix it by caching our editing and doing conditional setUser in useEffect.</p><p>Imagining our data flow is way more complex, two sources of truth would lead to a bigger problem, and really hard to track.</p><p>However, it’s not an anti-pattern if you make it clear that the prop is only to seed data for the component’s internally-controlled state.</p><p><strong>Derived state</strong> is sparingly used, for the best, only use it when your component’s internal states don’t need to sync with props from a parent, or even when you need a sync, remember don’t do <strong>unconditional state update</strong>, always check your logic, find out if it needs any condition.</p><h3><strong>Accidentally mutate props</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*SyWtefssUlPLkHcgWLLmOw.jpeg" /></figure><p>Every framework has its own ecosystem and set of rules. These rules are set to ensure developers don’t break the vision/ecosystem of the framework. So does React, the update process of it is mainly asynchronous. From the beginning, we are taught not to mutate state/props directly, the process must be asynchronous, and React educates it by teaching us to use this.setState, or dispatch React<em>.</em>SetStateAction (2nd value of the returned tuple from useState), I did explain to them clearly <a href="https://javascript.plainenglish.io/react-native-the-state-world-59721cbf0521">why it is asynchronous</a>? in my previous blog post, and Redux also gives this as one of the main rules in their documentation. These emphasize the importance of not mutating state/props directly, a must-follow rule.</p><p>That being said, everyone at least makes mistakes once, it could be a lack of knowledge, or carelessness, or lack of support from programming tools. Resulting in logical bugs when your app doesn’t work as expected, or your components do not render correctly. Let’s find out why!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUVQCD8DDEdpgZ6hEqz7KQ.png" /></figure><p>For example, our Greeting component, let’s say it can display some text like “Hello 31/12/2021” and uses props.date to initial dateState — derived state. In updateYear function, we want to update the year of dateState. Usually, we make changes to copy of object so that it won’t affect the object, but sometimes, in a rush, we forgot and do something like :</p><pre>const newDate = dateState<br>newDate.year = newYear</pre><p>This affects to props.date, mutating it directly, and because today, newDate, dateState, props.date have the same reference, we accidentally change today. Let’s say, I have other components used today for some calculation, after one more update batch, the calculation suddenly generates the wrong result, without experience, newbies would struggle to find out.</p><p>So remember to make changes on a copy of an object while working with a <strong>derived state</strong>, and be careful choosing how to make a copy, there are multiple choices, the decision between <strong>deep copy</strong> and <strong>shallow copy</strong> in Javascript.</p><h3>Summary</h3><p>Derived State is an anti-pattern, yet it’s still a good approach when we need temporary mutation on our data, and for this case, I assume it’s the most simple approach out there.</p><p>Two sources of truth are hard to manage than a single source of truth, of course. It’s the most ideal to use derived state when your component won’t care about the update from parent’s props (the props used for derived state), or if you really need to sync between state and props, remember not to unconditionally update.</p><p>Mutating props directly is problematic, must update derived states carefully, especially when your states are objects.</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><em>free weekly newsletter</em></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><em>community Discord</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1491a9ee3a6b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-derived-state-in-react-1491a9ee3a6b">Understand Derived State in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusability patterns in React]]></title>
            <link>https://javascript.plainenglish.io/reusability-patterns-in-react-9c8ff2e29ef6?source=rss-c853f5a06ee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c8ff2e29ef6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kush Tran]]></dc:creator>
            <pubDate>Sun, 04 Jul 2021 23:53:38 GMT</pubDate>
            <atom:updated>2021-07-09T06:02:02.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reusability Patterns in React</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Ofq8598zjL7tTH5QSNAoWA.jpeg" /><figcaption>Avengers gonna hate this !</figcaption></figure><p>Short opening: Yeah, we are going to deep dive into reusability together!</p><p>Long opening: Once, my MacBook was drenched in Coca-Cola, and the keyboard was sticky as hell. I could barely type. I really hated typing different versions of a function over and over again. My keyboard couldn’t afford that, sadly :(</p><p>I knew there had to be a better way.</p><p>Programming is like a baby; as parents, we must prepare for it to grow, evolve and expand. There is no perfect code, you know! Still, it’s just that one baby, with different “versions”. “Rebirthing” it constantly seems to be an awful solution.</p><p>Talk about effort! We haven’t even discussed maintenance yet. We don’t want something hard to handle, like the Avengers don’t want to fight 9 versions of Thanos at the same time 😊. We want easily maintainable pieces of code.</p><blockquote>This long article discusses different approaches to solve duplication of component logic in React. The below examples &amp; implementations could be ridiculous and weird sometimes. But just stick to it ! We just take advantage of it to point out the weakness of the mentioned patterns. So this will be more about learning the aspects. Thanks!</blockquote><p><strong>Table of contents:</strong></p><ul><li><strong>The problem</strong>: get to know the problem of repeating logic in components.</li><li><strong>Higher-Order Component</strong>: we use HOC to handle the problem, know the downside.</li><li><strong>Render Prop</strong>: we use Render prop to handle the problem, props and cons</li><li><strong>Custom Hook</strong>: my best choice to solve the problem at the moment, let’s see why i love it.</li><li><strong>Recap !</strong></li></ul><h3>The Problem ! Why should we care ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*i5bgtli0V6jlm_U57_yvHA.jpeg" /></figure><p>React offers great reusability, thanks to Component model &amp; Composition, we can easily reuse UI parts at different places in our app/web. They also care about reusing logics inside components. As you know that, not every component is dumb, we can leverage great features like State (mostly) to make our components become smarter, owning logics. Usually, smart components own similar logic, duplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*TxnTcepIkuGvCgFiIJPVPw.png" /></figure><p>Let’s say we have a Switch button, a dropdown menu, another button showing modal. They can be on the same screen or on different screens, and let’s assume there is always text input with the keyboard showing there. With each button, we have a toggle function to on/off the switch, show/hide the dropdown menu and open/close the modal. For great UX, we want every time we do action with our buttons, the keyboard must be closed, and we need forwarding our Ref to the components (buttons) to leverage some of its function.</p><p>In brief, we have 3 main features for our buttons. <strong>Toggle, Keyboard Close, Fowarding Ref.</strong></p><p>A basic implementation of our buttons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*TT7_g4oGXs7Ry1vSwmRzzg.png" /></figure><p>You notice that there is one duplication part over the three implementations. These buttons aren’t identical, even the initial state got from a different source of props, one from props.value and one from props.visible, but they share similar logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*qvA8Jby-xXcDxhISqyZxsQ.png" /></figure><p>These functions are too basic and short to concern about.</p><p>But imagine once these functions become huge with complex &amp; complicated calculations, with a much longer version. Which takes much effort to write, and how you will update all of it with new changes? Do you make a change of one and copy/paste it to another ? That would be much effort tracking the location, even worst there could be some mistake during the copy process, create buggy code. As new developers take up the project, they’re not the author of these lines of code, they won’t know there are other versions of it at other places. Talking about maintenance, it is a pain, obviously !</p><p>The reason i implement these short functions is to raise awareness. Short logic can be big someday. Usually, we don’t think a logic will appear in many places or become a monster. Once it happens, don’t hesitate to refactor it, adding reusability! I suggest reading the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a> in programming. Now let’s get back to React.</p><p>Over years of evolving, React has come with many approaches to handle duplication logic. The well-known are <strong>Higher Order Component (HOC), Render Prop and Custom Hook.</strong> Why so many? What problem is there with the old approach? Why the new approach? Let’s find out!</p><h3><strong>Higher-Order Component (HOC)</strong></h3><p>Component transforms props into UI, whereas, HOC transforms a component to another component, with enhancement!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmTnlyYz1wOdC6_AvIWDkQ.png" /></figure><p>Having said that, HOC doesn’t modify your input component. HOC’s mission is to wrap your input component, like a container, and HOC doesn’t care how/why data is used, Component doesn’t care where data comes from. This is important, because it serves <strong>composition </strong>purpose, meaning easy to change &amp; modify between components.</p><p>Back to our example, let’s write a withToggle HOC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Sr4qUSaEaG1oreFK7RdcNg.png" /></figure><p>withToggle handles the toggle logic and provide it for WrappedComponent. It needs to pass toggle and onToggle down to WrappedComponent.</p><blockquote>I’m not writing onToggle here , let’s just focus on talking about 1 prop — toggle — because the explanation eventually the same for both.</blockquote><p>Basically, HOC is just a function with component output, so the way to implement it can be various ways, it depends on our creativity in programming, we can actually have numerous parameters. You can look at <strong>connect()</strong> of Redux, a really famous HOC.</p><p>Every part is written intentionally to point out the downside, let’s find out!</p><h4>#1 ISSUE: WRAPPER<strong> HELL</strong></h4><p>Imagine one day, our component become multi-feature, and wrapped around by 10 HOC, how ugly would it be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*BOO7aKNhAlyIdSdv99GTyg.png" /></figure><p>Yeah I know, it’s a monster.</p><p>Talking about readability, it’s hurt my eyes, I might retire so soon reading these codes every day. Hard to read means hard to maintain, we will eventually take the pain.</p><p>Talking about debugging and writing tests, we need to dive into every HOC to see the implementation, and imagine they’re like nodes. To know exactly how the component behaves, we need to connect these nodes together, complicated right?</p><p>So this is a totally bad experience, which leads to the next issues.</p><h4><strong>#2 ISSUE: FIXED AND OVERLAP PROPS</strong></h4><p>Talking about fixed prop, as withToggle use props.value inside its implementation, we have to pass initialState to EnhanceButton as value prop. It would fail if we pass whatever differs from value, it’s fixed</p><pre>const EnhanceButton = withToggle(SwitchButton)</pre><pre>&lt;EnhanceButton value={initialState}/&gt;</pre><pre>// inside withToggle</pre><pre>const withToggle = (component) =&gt; (props) =&gt; {<br>  const [toggle, setToggle] = useState(props.value)<br> .....</pre><pre>}</pre><p>Another way we can pass the initialState to withToggle as function arguments, which I will talk about below. But for now, let’s keep it because fixed prop like value happens a lot, and worse, with nested HOCs, it’s the main cause of overlap prop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*s15BcnC4ZYz1_I2LDmKSQg.png" /></figure><p>My fellow MacBook users, I bet there have been many times you guys seeing this warning!</p><p>Yes, duplication!</p><p>Let’s saying our nested HOCs are shaping a wrapper hell, and some of them use the same props name, what will happen ? Apparently, they will replace/overlap each other, without warning us. Our computer is so nice giving us the warning and provide many options, but React doesn’t work that way sadly.</p><p>Naming has already become a hard question in programming, this makes it more complicated, not only we have to think about how to name it, but also avoiding duplication, funny like solving duplication in duplication lol :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*cvpAGzjfjI1un20SWWBntQ.jpeg" /></figure><p>No one likes surprise happening in their code. 😂</p><h4>#3 ISSUE: OUTER REF MASKS INNER REF</h4><p>If you notice, i use React.forwardRef in our withToggle HOC. Because HOC is just a container, common problem praised by the community that they have given the component the ref, but it is not working!</p><p>Apparently, our WrappedComponent is like a child of HOC, so giving ref like:</p><pre>const btnRef = useRef(null)</pre><pre>&lt;EnhanceSwitchBtn ref={btnRef}/&gt;</pre><p>Our SwitchButton not receiving the ref, we need to forward it down to the SwitchButton. This is not actually an issue, it’s more a remind !</p><h4>#4 ISSUE: DYNAMIC DATA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*W_V00t-A9QJw58ClIcccSA.png" /></figure><p>Wondering why I have these comments here?</p><p>Inside SwitchButton: we have something like:</p><pre>&lt;Switch value = {toggle}/&gt;</pre><p>Since we move to using HOC, toggle is passed to SwitchButton from withToggle (the part toggle = {toggle}) =&gt; Inside SwitchButton will become</p><pre>const SwitchButton = () =&gt; {<br>   return &lt;Switch value = {props.toggle}/&gt;<br>}</pre><pre>//similar to inside ModalButton</pre><pre>const ModalButton = () =&gt; {<br>   return &lt;...&gt;<br>      &lt;Modal visible = {props.toggle} /&gt;</pre><pre>     &lt;/...&gt;</pre><pre>}</pre><p>Similarly, ModalButton behaves the same way.</p><p>But if i want something more transparent, like:</p><pre>const SwitchButton = () =&gt; {<br>   return &lt;Switch value = {props.value}/&gt;<br>}</pre><pre>//similarly inside ModalButton</pre><pre>const ModalButton = () =&gt; {<br>   return <br>       &lt;...&gt;<br>         &lt;Modal visible = {props.visible} /&gt;</pre><pre>       &lt;/...&gt;</pre><pre>}</pre><p>WrappedComponent (SwitchButton, ModalButton) is passed toggle as a prop, we can’t pass value, visible the same time, and if we need more props like this case, our HOC will be ugly. We can do that! But it is not recommended!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*FTwrSmH5ccRnfVW20VOpcA.png" /></figure><p>Once we create an abstraction like HOC, it forces us to define a general rule, we have to modify our component to receive props.toggle.</p><p>WrappedComponent is like a place where we will fit many components in. So we can’t serve only one component and abandon other. Apparently, HOC is not flexible with output data.</p><p>This is one of the reasons the next <strong>Render Prop</strong> approach solves, but let’s wait till we discover it below.</p><p>On the other hand, HOC work well with dynamic input data. Let’s saying we have two list components, leverage data the same way, same logic, we want a withData HOC to handle the logic for it, and leave us the right to choose input data. We can pass data as parameters or derive it from props.</p><pre>const withData = (component, inputData) =&gt; (props) =&gt; {<br>   const [data, setData] = useState(inputData)</pre><pre>}</pre><pre>const EnhanceHourList = withData(ListComponent, DataStore.getHour())</pre><pre>- or</pre><pre>const withData = (component, selectData) =&gt; (props) =&gt; {<br>   const [data, setData] = useState(selectData(props))</pre><pre>}</pre><pre>// get different hours by country ID</pre><pre>const EnhanceUSHourList = withData(ListComponent,<br> (props) =&gt; DataStore.getHour(props.countryID))</pre><pre>const EnhanceJapanHourList = withData(ListComponent,<br> (props) =&gt; DataStore.getHour(props.countryID))</pre><p>It’s pretty good for customizing, isn’t it?</p><p>Overall, HOC has props and cons like any concept, nothing is perfect. And it’s been serving us well in development, so anyway good job HOC ❤️❤️ I have to admit that HOC is great solution at the very first years of React, before other dominant approaches coming out. Not wasting any of your time, let’s see next how Render Prop solves our situation!</p><h3>Render Prop</h3><p>Render Prop is another technique to reuse logic like HOC. As its name, this is a technique leveraging the render part. This technique lets you decide how to render that “prop” — whatever output data, meaning it doesn’t care about what to render, you are who decides it!</p><blockquote>A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.</blockquote><pre>&lt;DataProvider render={data =&gt; (<br>  &lt;Text&gt;Hello {data.name}&lt;/Text&gt;<br>)}/&gt;</pre><p>DataProvider is a render prop, it provides us data, and we can use it to render anything we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*yugeZESpm3Wa1CHGwE8tdA.png" /></figure><p>Back to our example! In ISSUE #4 (scroll above), where we discuss how inflexible HOC is when dealing with output data. Apparently, we demand to use our data however we want without sticking to any general rule. <strong>Render Prop</strong> is here to help.</p><p>Let’s re-write our withToggle HOC in Render Prop way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*LvjEHyWpGgbri0qyVIWEHw.png" /></figure><p>Let’s call it ToggleProvider as it provides the children with toggle. Unlike HOC, which joining in shaping our children — render part — , Render Prop doesn&#39;t care.</p><pre>&lt;ToggleProvider&gt;<br>  {({toggle, onToggle}) =&gt;<br>         &lt;SwitchButton <br>           onValueChange={onToggle}<br>           value={toggle}/&gt;<br>  }<br>&lt;/ToggleProvider&gt;</pre><pre>&lt;ToggleProvider&gt;<br>  {({toggle, onToggle}) =&gt; <br>        &lt;ModalButton <br>          onPress={onToggle} <br>          visible={toggle}/&gt;<br>  }<br>&lt;/ToggleProvider&gt;</pre><p>Every child of ToggleProvide can then use toggle, onToggle to render whatever it needs. We don’t need to set out a general rule like in issue 4, our SwitchButton and ModalButton can now use value, visible prop directly without setting up another toggle prop.</p><p>Provide reminds me of <a href="https://reactjs.org/docs/context.html"><strong>Context API</strong></a>. If you haven’t known it yet, it’s solving deep updates in our application. We can see that <strong>Context</strong> is designed base on <strong>Render Prop</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5syj7n7Gd0RooA_l_Dykew.png" /></figure><p>We can clearly see that, especially in their <strong>Consumer</strong>. I think this is interesting to note, as knowing how other familiar techniques is implemented is cool, right ? Another fact that Render Prop is not only great at reusing logic but also delivering data.</p><h4>Composition Ability</h4><p>We know that React is great at composing, which helps to break large problems into smaller parts. Render Prop empowers this ability, providing us stronger tool. We’ve been talking about reusing logic, which Render Prop handles pretty well, but another advantage is to make our component more flexible by letting us passing UI part into another component.</p><p>Why is this beneficial? Let’s go through an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1uAd-z_99bR2w9D2gIvVQ.png" /></figure><p>Saying we have 3 different styles of header in our app, in our code, would look like:</p><pre>const NavHeader = (props) =&gt; {</pre><pre> return(<br>  &lt;View&gt;<br>   &lt;Left/&gt;<br>   &lt;Title/&gt;<br>   &lt;Right/&gt;<br>  &lt;/View&gt;</pre><pre>)}</pre><p>Writing a 3-in-1 right component could be:</p><pre>const Right = (props) =&gt; {<br> switch(props.type): {<br> case &#39;icon&#39;: return &lt;Icon/&gt;<br> case &#39;text&#39;: return &lt;Text/&gt;<br> default: return null</pre><pre> }}</pre><p>This could work pretty well at first, but we don’t know what update in the future will affect our component. The approach seems too fixed to scale. Ideally, i want NavHeader to render what I tell it to.</p><pre>const NavHeader = (props) =&gt; {<br>return(<br>  &lt;View&gt;<br>   {props.renderLeft()}<br>   &lt;Title/&gt;<br>   {props.renderRight()}<br>  &lt;/View&gt;<br>)}</pre><pre>&lt;NavHeader<br>renderLeft={...}<br>renderRight={&lt;Icon/&gt; or &lt;Text/&gt; or null}<br>/&gt;</pre><p>With this approach learning from <strong>Render Prop</strong>, we’re more open to future changes, and able to avoid writing complex components like Right above.</p><h4>Deeply passing prop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuB17rnT_mK6mbeDJgxTwQ.png" /></figure><p>Let’s say we have this ProfileScreen</p><p>ProfileScreen contains different information about myself.</p><p>It might have different contents like Header, Body, Footer. But we just focus on the Body for this example, which named ProfileBody</p><p>Inside ProfileBody, we have my profile avatar, my name and my body stats. BodyStats describe stats about my body.</p><p>BodyStats will receive my user data and use that to render the layout.</p><p>Alright, done! Now let’s do some code.</p><pre>const ProfileScreen = (props) =&gt; {<br> return &lt;View&gt;<br>         ...<br>         &lt;ProfileBody user={props.user}/&gt;<br>         ...<br>      &lt;/View&gt;<br>}</pre><pre>const ProfileBody = (props) =&gt; {<br> return &lt;View&gt;<br>         ...<br>         &lt;BodyStats user={props.user}/&gt;<br>         ...<br>      &lt;/View&gt;<br>}</pre><pre>const BodyStats = (props) =&gt; {<br> return ...<br>}</pre><p>Normally, we have that structure like above. The implementation shows the <strong>prop drilling</strong> issue, we pass our user data down to the BodyStats through many layers.</p><p>ProfileScreen — — &gt;ProfileBody — →BodyStats</p><p>To deal with <strong>prop drilling</strong>, we can leverage <strong>Context API</strong> or state management like <strong>Redux </strong>to access user anywhere we want without passing it deep down. But let’s keep it for complicated situations, assuming this only for rendering body stats, let’s do it in an easy way by using <strong>Render Prop.</strong></p><pre>const ProfileScreen = (props) =&gt; {<br> return &lt;View&gt;<br>         ...<br>         &lt;ProfileBody bodyStats={&lt;BodyStats user={props.user}/&gt;}/&gt;<br>         ...<br>      &lt;/View&gt;<br>}</pre><pre>const ProfileBody = (props) =&gt; {<br> return &lt;View&gt;<br>         ...<br>         {props.bodyStats()}<br>         ...<br>      &lt;/View&gt;<br>}</pre><p>By doing this, we remove the need of passing user down to children components. As we going, it’s obvious that <strong>Render Prop</strong> is a great technique for Composing and passing prop. Composition is dominant for creativity, letting us expand further ability in programming, as you can see, either lifting up or passing down is pretty easy, and is really good at adapting to changes! And in my opinion, <strong>Render Prop</strong> has the best ability in <strong>customization.</strong></p><p>Clearly, it depends on our requirement and behavior to choose the right structure. For example, saying we add edit feature for body stats, which we want only BodyStats component update without calculating/re-rendering layout tree of ProfileBody &amp; ProfileScreen to boost performance (might due to the costly re-rendering process). That is another problem to solve, which in my opinion, not ideally to use <strong>Render Prop</strong>. Okay, let’s leave that problem behind, back to our example. Shall we discuss the downsides now?</p><h4><strong>#1 ISSUE: Locked Data</strong></h4><p>The biggest problem of Render Prop is the passed data get locked inside rendering.</p><pre>const ParentComp = () =&gt; {</pre><pre>// outside field</pre><pre>return (<br> &lt;ToggleProvider&gt;<br>  {({toggle, onToggle}) =&gt; {<br>  //...usage scope</pre><pre>return &lt;SwitchButton onValueChange={onToggle} value={toggle}/&gt;</pre><pre> }}<br> &lt;/ToggleProvider&gt;</pre><pre> // or custom prop</pre><pre> &lt;ToggleProvider</pre><pre> renderContent={({toggle, onToggle}) =&gt; {<br>    //...usage scope</pre><pre>   return &lt;SwitchButton onValueChange={onToggle} value={toggle}/&gt;</pre><pre> }}/&gt;</pre><pre>)}<br></pre><p>Even you use children or whatever custom prop (like renderContent, or anyPropYouLike), the passed data toggle, onToggle will be available to use inside usage scope, and inside component implementation. This restricts us from using the data at outside field</p><p>The demand is true, sometimes we want to use data as state or calculate something base on it. Having said that, we can still manage to do it without some fix like passing it to a callback or any way you feel it works; it’s your own creativity, overall, that might be ugly to do.</p><h4>#2 ISSUE: Nested Render Prop — Wrapper Hell</h4><p>We’ve seen wrapper hell happens with nested HOC. We have a similar problem with render prop.</p><pre>&lt;ToggleProvider&gt;<br>  {({toggle, onToggle}) =&gt; {</pre><pre>   return &lt;DataProvider&gt;</pre><pre>        {({data}) =&gt; {<br>  <br>          return &lt;AccessProvider&gt;</pre><pre>           {({access}) =&gt; {<br>            return &lt;OurComponent/&gt;</pre><pre>           }}   <br>          &lt;/AccessProvider&gt;</pre><pre>        }}   <br>    &lt;/DataProvider&gt;</pre><pre>  }}<br> &lt;/ToggleProvider&gt;</pre><p>Let’s saying we have 3 render prop nesting like above, the readability is sure brutal. One thing I love about <strong>JSX</strong> and <strong>React Native</strong> is that they provide a declarative way to write layouts. I love how we can write it clean. If you ever use <strong>StyleSheet</strong> to avoid <strong>inline style</strong>, or break down the large UI into smaller containers, you know what I&#39;m saying. Aside from the technical benefits we get from doing so, our eyes also get rested.</p><p>This reminds me of asynchronous in programming with the usage of then. Before the advent of await and async keyword. We’ve seen this callback hell a lot. Let’s find out below how we can handle this with a <strong>custom hook</strong>.</p><h4>#3 ISSUE: Break Render Optimization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*QSCEdHtOtn34JIfLOvlsFg.jpeg" /></figure><p>Wasted rendering happens a lot during working with React. Talking about optimization, we can either make it run faster or do less work. About React, we are usually doing less work, and for wasted rendering, mainly we skip rendering. If you want to know more about how it happens and the solution, you can read my <a href="https://javascript.plainenglish.io/react-native-why-props-references-break-optimizations-79c463ca0723">article</a>.</p><p>Shortly, React provides 3 ways to optimize: shouldComponentUpdate life cycle, React.memo and PureComponent. Although they’re different techniques, they share the same fundamental, using shallow compare. So object reference plays an important part here.</p><pre>&lt;ToggleProvider&gt;<br>  {({toggle, onToggle}) =&gt; {<br>  return &lt;SwitchButton onValueChange={onToggle} value={toggle}/&gt;</pre><pre>  }}<br>&lt;/ToggleProvider</pre><p>By the nature of <strong>Javascript</strong>, either way of using <strong>Render Prop</strong> generates new reference every time it diffs in rendering process, resulting in breaking our render optimization.</p><p>We don’t always need optimization for our components, but please note this once you have to do it, and handle careful these object reference because <strong>premature optimization</strong> is a root of the devil.</p><p>Despite the downside, I believe <strong>Render Prop</strong> still has its own value in React world, until now I think it is the best for customization! — Reading more below, we will discuss it, before that, first going with me through <strong>Custom Hook</strong> section.</p><h3>Custom Hook</h3><p>Hooks were announced in 2018, if i remember correctly. It was the hit of the year for React. Clearly, the hotness is due to how it helps coding React more pleased and satisfied. Aside from the default hooks provided by React team, they let us create our own hooks, custom hooks, which become its strongest feature. Like creating a market and allow people to produce and sell their products on it, pretty community-driven!<a href="https://usehooks.com/"> usehooks.com</a> is a great site for helpful custom hooks, check that out!</p><p>Show me some code!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*ZktwL3Fr8n_N0opQVK9vug.png" /></figure><p>useToggle is our custom hook, which handle the logic of initializing &amp; updating the toggle for us, by common convention, we should name it with use at the beginning. And it’s easy to use:</p><pre>const Screen = () =&gt; {<br>  const [toggle, onToggle] = useToggle(false)</pre><pre>  return(<br>   ....<br>   &lt;SwitchButton onValueChange={onToggle} value={toggle}/&gt;<br>   ....<br>  )<br>}</pre><p>A custom hook can return some value or just a pure function, it depends on how we implement it, and it’s strictly to follow any return structure, we can return any structure as we’d love.</p><h3>No more Wrapper Hell</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*e6zgn1JnsFz1VyLH27pOzw.jpeg" /></figure><p>We’ve seen wrapper hell in HOC and Render Prop when they deal with nested problem. Custom hook doesn’t work that way, because it doesn’t wrap anything, it’s like a render-less component, with return null for render. Like we just need the content, we don’t care about else. Yup! Buying stuff with no box :)</p><p>And the usage of custom hook looks like writing one line of code, it’s more like many consecutive lines of code than wrapping up each other.</p><pre>const [toggle, onToggle] = useToggle(false)<br>const data = useFetchData(params)<br>useClickAway()<br>useHandleKeyboard()</pre><h3>Flexible Data Usage</h3><p>One advantage makes Custom Hook dominant than other is the flexibility. As we learn from above techniques, they sometimes too fixed in data usage, Hook is not ! The data flow of hook is extremely flexible.</p><h4><strong>1/ No fixed props</strong>:</h4><p>Remember our withToggle HOC and Issue 2 ? It uses props.value as an initial state.</p><pre>const EnhanceButton = withToggle(SwitchButton)</pre><pre>&lt;EnhanceButton value={initialState}/&gt;</pre><pre>// inside withToggle</pre><pre>const withToggle = (component) =&gt; (props) =&gt; {<br>  const [toggle, setToggle] = useState(props.value)<br> .....</pre><pre>}</pre><p>Shortly remind you , in the implementation of withToggle, It uses props.value as an initial state. So when writing JSX of EnhanceButton, we have to pass down initialState as value prop, it would fail if we pass whatever differs from value, it’s fixed.</p><pre>const Screen = () =&gt; {<br>  const [toggle, onToggle] = useToggle(false)</pre><pre>return(<br>   ....<br>   &lt;SwitchButton onValueChange={onToggle} value={toggle}/&gt;<br>   ....<br>  )<br>}</pre><p>By using custom hook, as initial state is passed as function arg, we’re more open to define our initial state, we remove the need of passing initial state as prop to component.</p><h4>2/ No overlap props:</h4><p>We also talked about how<strong> fixed prop</strong> and <strong>nested HOC</strong> lead to <strong>overlap prop </strong>above. Because <strong>wrapper hell</strong> doesn’t happen in custom hook, and neither <strong>fixed prop </strong>-&gt; we don’t have to aware of this anymore!</p><h4><strong>3/ No restriction for data usage scope</strong></h4><p>What happens to Render Prop is the usage scope of our passed down props which we discussed in<strong> ISSUE 1: Locked Data.</strong></p><pre>const [toggle, onToggle] = useToggle(false)<br>const data = useFetchData(params)<br>useClickAway()<br>useHandleKeyboard()</pre><p>Looking these custom hooks, useFetchData and useToggle are the hooks providing us data for rendering or calculation, depends. It exposes data out of its implementation and give it to us, so we can freely use data anywhere we need, not anymore restricted inside render like <strong>Render Prop.</strong></p><h4>4/ No general rule for output data:</h4><p><strong>ISSUE 4 of HOC</strong> we mentioned above showing how we need a general rule for passing data down to WrappedComponent, because our HOC will wrap many kinds of components. I also showed how Render Prop fixes this</p><p>As mentioned above, the way hook exposes data out of implementation empowers the freedom of passing down data as props to children components. We can pass data to any prop we want, as long as, it’s appropriate.</p><pre>const [toggle, onToggle] = useToggle(false)</pre><pre>&lt;SwitchButton <br> onValueChange={onToggle}<br> value={toggle}/&gt;</pre><pre>&lt;ModalButton <br> onPress={onToggle} <br> visible={toggle}/&gt;</pre><h3>Customize Ability</h3><p>Component is a creative playground, where we leverage React concepts as materials, and custom hook is one of those.</p><p>The usage of custom hook is not always the same, sometimes we need to add logic to see whether we need to use it, like a condition. As a rule of hook, we can’t call hooks inside of conditionals, loops, or nested functions in order to ensure that Hooks are called in <strong>the</strong> <strong>same order</strong> each time a component renders. Why this important?</p><p>Due to the internal implementation of React Hook, the order is important, like i mentioned in <a href="https://javascript.plainenglish.io/react-native-the-state-world-59721cbf0521">my blog post</a>. There is an array storing names of hooks and this array is used to do stuff, like updating. So rules are set out to ensure the order of this array is kept over renders.</p><p>Conditions, loops, or nested functions lead to a different order, so that’s why they prevent it.</p><pre>const Component = (props) =&gt; {</pre><pre> const [toggle, onToggle] = useToggle(false)<br> const data = useFetchData(params)</pre><pre> if(props.enableKeyboard){<br>  useKeyboardHandler()<br> }<br>}</pre><p>Saying we have a component using 3 hooks useToggle, useFetchData and useKeyboardHandler. useKeyboardHandler is optional, we don’t need handlers for keyboard in case disable keyboard, it’s a waste, and we determine it by enableKeyboard prop. This breaks the rule of hook. Because in case enableKeyboard = true, the order array will be [‘useToggle’, ‘useFetchData’, ‘useKeyboardHandler’], while enableKeyboard= false forming [‘useToggle’, ‘useFetchData’,]. The order differs, like I said, the order must be the same all the time.</p><p>This rule makes custom hook not as flexible as <strong>Render Prop</strong> when it comes to customize.</p><p>You can leave the useKeyboardHandler there, without condition, and apparently, it will do nothing in case keyboard is disabled (not like keyboard temporarily closing, it’s like never appear keyboard). It works!</p><p>Either way, we can turn it into render-less component, and use it as JSX coming along with the condition:</p><pre>// custom hook<br>const useKeyboardHandler = () =&gt; {<br>  useEffect(()=&gt;{<br>   // listen some keyboard events</pre><pre>   return () =&gt; {<br>   // clear out listeners</pre><pre>    }<br>  }, [])<br>}</pre><pre>// render less component<br>const KeyboardHandler = () =&gt; {  <br> useKeyboardHandler()<br> <br> return null</pre><pre>}</pre><pre>// in JSX </pre><pre>{props.enableKeyboard &amp;&amp; &lt;KeyboardHandler/&gt;</pre><p>In details, useKeyboardHandler is a custom hook saying we listen to keyboard events (open, dismiss) and do some logic, at un-mounting we want to clear out listeners. We write a render-less component, this component doesn’t output/render UI layout, it just calls our custom hook. This remove the need of condition when calling useKeyboardHandler. Lastly, we use the conditional to determine whether we should render KeyboardHandler component.</p><p>Clearly, useKeyboardHandler is a hook without providing any data, so we can use render-less component to deal with it. But in the case of hooks like useFetchData, it provides data, we will have to use Render Prop to solve it:</p><pre>// render less component<br>const FetchData = (props) =&gt; {  <br> const data = useFetchData()<br> <br> return props.children({data})</pre><pre>}</pre><pre>// in JSX<br>{props.enableFetchData &amp;&amp; <br>    &lt;FetchData&gt; <br>     {({data}) =&gt; do some thing }<br>    &lt;/FetchData&gt;<br>}</pre><p>Alright! I know it’s very rare case to deal with conditional hook, even in my real work, i don’t see it much. But if it happened, I’m happy knowing how to solve it. Not sure if there were any other approaches to solve this, but these are 2 ways I&#39;ve learned.</p><h3>Recap</h3><p>It’s great you’ve come to the end of this long article with me, I believe we’ve learned a lot through this discussion.</p><p>Every technique has its own pros and cons, it depends on our choices. I’m not biased but custom hooks are my favorite at the moment. There is more to discuss, like talking about testability, writing tests, custom hook seems not as easy as HOC, Render Prop. That’s for another time! See you in my next article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c8ff2e29ef6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/reusability-patterns-in-react-9c8ff2e29ef6">Reusability patterns in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The most complete guide to React State you’ll ever read]]></title>
            <link>https://javascript.plainenglish.io/react-native-the-state-world-59721cbf0521?source=rss-c853f5a06ee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/59721cbf0521</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[usestate]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Kush Tran]]></dc:creator>
            <pubDate>Mon, 11 Jan 2021 20:29:01 GMT</pubDate>
            <atom:updated>2021-01-14T04:35:30.668Z</atom:updated>
            <content:encoded><![CDATA[<h4>The World of React + React Native State 🌍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tnW9L0PjS7_eC4BXF8zPBQ.jpeg" /></figure><p>When i first learned about <strong>State</strong>, it is so friendly and simply just “data that is going to change + mutating it triggers a component rendering”. That’s what people told me.</p><p>After years working with it, i started perceiving the gap in my knowledge. The State I used to know, comes with more concepts &amp; related concerns that i only realized after hitting hardship &amp; lots of researching effort. Hardly had i found a post covering them all. So in this blog post, let’s break it down !</p><h4>Table of contents:</h4><ul><li><strong>The problem: </strong>What problem State solves?</li><li><strong>You probably don’t need State?:</strong> Decide when to use State wisely.</li><li><strong>The big rendering picture: </strong>How State relates to the rendering process, how it is a part of the rendering picture.</li><li><strong>Why Asynchronous? Reasons behind API design: </strong>Batching, Internal Consistent, Concurrent Updates?</li><li><strong>Side Effect: </strong>Properly handle side effect.</li><li><strong>Placing your State effectively: </strong>How placing state boosts your performance.</li></ul><h3>The Problem</h3><p>Props are great materials for customizing components. But everyone knows it is <strong>immutable, can’t be mutated</strong>, which prevents the flexibility because in real world example, a component sometimes need to change over time.</p><p>State is a part of a component born to store data that gonna changes, and component reacts to those changes.</p><p>For example, water boils at 100C, and freezes at 0C. The temperature changes that decides the water’s state. The temperature here is like a State, and the water is like a component, this component reacts to the change of State.</p><h3>You probably don’t need State?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yg-nRleqz12xklll8HLJoA.jpeg" /></figure><p>In case of <strong>mutate data</strong>, lots of people struggle with deciding when to use State, when not to use. If you haven’t known yet, State relates closely to triggering a re-render, and storing data into State unnecessarily triggers “wasted renders”.</p><p>I divide the usage of <strong>mutate data</strong> into two category:</p><ul><li>The data that relating to render: used or related to the work of generating UI output.</li><li>The data that not relating to render: just simply used to store some data, for later calculations,…completely not related to generating UI output.</li></ul><h4>And the rule always is: <strong>Only use state to store mutate data that relate to rendering.</strong></h4><p>Because with data not relating to render, we don’t need to display it to the UI tree, so there no need to queue a re-render process, calculate the UI tree.</p><p>Otherwise, when it relates to render, mutating the state data queues a re-render process, which outputs the new tree UI and React will diff that tree to collect changes, then update to the real tree.</p><p>Let’s break down a simple example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yqHuOC0HhWYpFrPJISZsw.png" /></figure><p>In above example, saying i have three buttons, two of which display the number of counts, including one will display double if <strong>isDouble</strong> is true.</p><p>The third button shows whether <strong>isDouble</strong> is ON or OFF.</p><p>Every time i press on any of the two buttons, the <strong>count</strong> value then increase by 1, and <strong>btnPressed</strong> records the position of the button just pressed. And pressing on the third button will toggle <strong>isDouble </strong>between ON or OFF.</p><p><strong>Count</strong> is used for displaying, so it’s related to rendering → store to State.</p><p><strong>isDouble</strong> is not used for displaying, but it decides the display value: ON or OFF, and decide whether count should be doubled, so it’s related to rendering → store to State.</p><p><strong>btnPressed</strong> is just a normal data storing position, it’t neither displayed or deciding any displaying, so it’s not related to rendering → do not store to State.</p><p>With data like <strong>btnPressed:</strong></p><p>For class component, you can use<strong> instance variables </strong>to store it</p><p>For function component,<strong> </strong>you can either use<strong> outside function variables or useRef </strong>to store it. The difference between them can motivate to write a separate blog post, so i won’t go into detail here, you can search it online.</p><p>Okay, one more time, with me</p><blockquote><strong>Only use state to store mutate data that relate to rendering.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*TKdpll3mECJcsSBKXEt8GQ.jpeg" /></figure><h3><strong>The big rendering picture (Bonus information, you can skip if you aren’t interested)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CfaYxw2J1ysUZlPOZ_ecDA.jpeg" /><figcaption>This is the current life cycles at the time this post written</figcaption></figure><p>React has lots of different core concepts. Altogether, they form a big picture of rendering. Those concepts relate closely to each other.</p><p>Today post is about State, so let’s see how State is a part of the big picture through three main phase: (not actual phases of rendering process, just my naming lol )</p><ul><li><strong>The initial phase:</strong> when State of a component first created.</li><li><strong>The update phase:</strong> when changing State by <strong>setState</strong> or setter of <strong>useState</strong></li><li><strong>The destroy phase:</strong> when a component unmount</li></ul><h3>— — — Class Component — — —</h3><h3>The initial phase:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtNUmAzxHleemv1xbYLYYA.png" /></figure><p>State is an asset of Component, when it comes to initial our State, we can either declare it inside <strong>constructor</strong> or make use of<strong> getInitialState.</strong></p><pre>// ES6</pre><pre>class Counter extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {count: 0};<br>  }<br>  // ...<br>}</pre><pre>// ES5</pre><pre>const Counter = createReactClass({<br>  getInitialState: function() {<br>    return {count: 0};<br>  },<br>  // ...<br>});</pre><p>The only difference between them is that <strong>getInitialState+createReactClass </strong>is the old legacy and <strong>constructor</strong> is the new way to initial state. React allow us do something like this:</p><pre>class Counter extends React.Component {<br>  this.state = {<br>       count: 0<br>  };<br>  // ...<br>}</pre><p>It’s eventually put into constructor so it’s the same.</p><p>After state has been initialed. The process moves on to <strong>getDerivedStateFromProps</strong>.</p><p><strong>getDerivedStateFromProps</strong> exists for only one purpose. It enables a component to update its internal state as the result of <strong>changes in props</strong>.(I’ll write in detail about this case in upcoming blog about The anti-pattern Derived State).</p><p>Then <strong>render() </strong>goes into action, running <strong>JSX</strong> to create <strong>ReactNode/ReactElement</strong>, forming out the first shape of our UI tree.</p><p>And <strong>componentDidMount</strong> comes behind that, at this point, React has updated <strong>refs and UI tree. </strong>This is important, because we might mistake using <strong>refs</strong> before this life cycles → resulting in <strong>undefined/null refs.</strong></p><p>On more interesting note about <strong>componentDidMount</strong>, it’s where we handle Side Effects like calling to APIs. Why is that?</p><pre>async componentWillMount(){<br> const response = await API.fetchList()<br> if(response.status == 200){<br>  this.setState({listData: response.data})<br> } else {<br> this.setState({error: response.error})<br> }<br>}</pre><p>The reason is to avoid <strong>undefined default state</strong>. Saying we fetch data before that, in the old <strong>componentWillMount(deprecated)</strong>. Fetching data most of the time, running asynchronous, so it’s no guarantee it will finish before <strong>render()</strong></p><p>And we use <strong>this.state.listData</strong> inside <strong>render()</strong>. And some silly time, we forget to initial default value of State → CRASH. So fetching in <strong>componentDidMount</strong>, like a reminder for us to initial default state value.</p><h3>The update phase:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*pAGbgPCh-9hUep6iH3pyGA.png" /></figure><p><strong>setState</strong> queues an update/rendering on Component, it’s a way to inform the component to start the update process. <strong>setState</strong> will trigger an update no matter the new state value has changed or not. While <strong>setter of useState </strong>checks this - using shallow equality for object.</p><p><strong>shouldComponentUpdate</strong> is a built-in life cycle provided as a way to optimize rendering (skip rendering) if return <strong>false</strong>, and for we not always need to optimize, its default behavior is return <strong>true</strong>.</p><p><strong>getSnapshotBeforeUpdate</strong> is invoked right before the most recently rendered output is committed to the real tree. It provide us access to prevProps and prevState for any special calculation to capture the render nodes before it is commited to the real tree, and the return value is passed to componentDidUpdate. Anyway, still not a common used life cycle</p><p><strong>componentDidUpdate</strong> is invoked right after the updating, not happening when first mounting component. Use this as an opportunity to handle side effects relating to the changing of new props &amp; state. If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate(). Otherwise this parameter will be undefined.</p><h3>The destroy phase:</h3><p>The name is already obvious guys ^^</p><h4><strong>— — — Function Component — — —</strong></h4><p>Since the release of <a href="https://reactjs.org/docs/hooks-intro.html"><strong>Hook</strong></a><strong> </strong>in React 16.8. It provides the capability of State for Function Component with the hook <a href="https://reactjs.org/docs/hooks-state.html"><strong>useState</strong></a>. Hooray !</p><pre>function Counter () {<br>  const [count, setCount] = useState(0);<br>...</pre><pre>}</pre><blockquote>With the power of Hook, personally, I don’t care about life cycles anymore, because reducing the amount of definitions/concepts is one of the reasons of Hook.</blockquote><h3><strong>Initial Phase</strong></h3><p>Different from Class, the nature of Function is <strong>captured value</strong>. So when a render happens, it re-run the function as well as redraw UI with its current version of data. Hook is likely to act as normal object having its own version for each renders.</p><pre>const hook: Hook = {   <br> memoizedState: null,   <br> baseState: null,   <br> baseQueue: null,   <br> queue: null,   <br> next: null, <br>};</pre><p><strong>useState </strong>is just one of the built-in Hooks. Basically they share the same object structure like above.</p><p>React will start <strong>mountState</strong> . Basic ideal is to mount a hook through <strong>mountWorkInProgressHook()</strong>, and it starts off like</p><pre>{   <br> memoizedState: null,   <br> baseState: null,  <br> baseQueue: null,   <br> queue: null,    <br> next: null, <br>}</pre><p>at the end hook become: (example with initial state = 0 )</p><pre>{<br>  memoizedState: 0, // our initial state<br>  baseState: 0, // our initial state<br>  queue: {<br>    last: null,<br>    dispatch: dispatchAction.bind(null, currentlyRenderingFiber, queue),<br>    lastRenderedReducer: basicStateReducer(state, action),<br>    lastRenderedState: 0, // our initial state<br>  },<br>  baseUpdate: null,<br>  next: null,<br>}</pre><p><strong>[hook.memoizedState, dispatch]</strong> are prepared to return for</p><p><strong>[count, setCount]</strong> = useState(0)</p><p>React exposes hooks to us as functions but under the hood, they are modelled as objects.</p><p>Here is the detail of <strong>mountState:</strong></p><pre>function mountState&lt;S&gt;(  initialState: (() =&gt; S) | S,): [S, Dispatch&lt;BasicStateAction&lt;S&gt;&gt;] { <br> const hook = mountWorkInProgressHook();  </pre><pre> if (typeof initialState === &#39;function&#39;) {   <br>  initialState = initialState();  <br> } <br> hook.memoizedState = hook.baseState = initialState;  </pre><pre> const queue = (hook.queue = {<br>   pending: null, <br>   dispatch: null,  <br>   lastRenderedReducer: basicStateReducer,  <br>   lastRenderedState: (initialState: any), <br> }); </pre><pre>const dispatch: Dispatch&lt;BasicStateAction&lt;S&gt;,  &gt; = (<br>queue.dispatch = (dispatchAction.bind(null,currentlyRenderingFiber,queue): any)<br>);  </pre><pre>return [hook.memoizedState, dispatch];<br>}<br></pre><h3>Update Phase</h3><p>Every time <strong>setCount </strong>(example above) triggers our component to re-render, the Hook memoize the new state, that’s way the fresh render updated with new Hook value.</p><p>Firstly, have a look again at our current hook value:</p><pre>{<br>  memoizedState: 0, // our initial state<br>  baseState: 0, // our initial state<br>  queue: {<br>    last: null,<br>    dispatch: dispatchAction.bind(null, currentlyRenderingFiber, queue),<br>    lastRenderedReducer: basicStateReducer(state, action),<br>    lastRenderedState: 0, // our initial state<br>  },<br>  baseUpdate: null,<br>  next: null,<br>}</pre><p><strong>dispatchAction.bind(null, currentlyRenderingFiber, queue) → currentlyRenderingFiber.</strong></p><p>Fiber is an object that is mutable, holds component state and represents the tree. React generate a tree of these objects, that’s how it models the entire component tree. I call it the representative of a component. <strong>Each component has its own Fiber. Fiber is used to identify component.</strong></p><p>Fiber has a property named <a href="https://github.com/facebook/react/blob/b53ea6ca05d2ccb9950b40b33f74dfee0421d872/packages/react-reconciler/src/ReactFiber.js#L125"><strong>memoizedState</strong></a>. Which stores the state of our <strong>Counter</strong> component. Its value is the hook object we created at <strong>mountState </strong>above, with the <strong>next</strong> and <strong>baseUpdate</strong> properties are null.</p><p>For example, if our Component got more hooks :</p><pre>function Counter () {<br>  const [count, setCount] = useState(0);<br>  const [check, setIsCheck] = useState(true);</pre><pre>...<br>}</pre><p>our <strong>memoizedState</strong> of <strong>Fiber</strong> will be:</p><pre>{<br>  memoizedState: 0, // the setCount hook<br>  baseState: 0,<br>  queue: { /* ... */},<br>  baseUpdate: null,<br>  next: { // the setIsCheck hook<br>    memoizedState: true, <br>    baseState: true,<br>    queue: { /* ... */},<br>    baseUpdate: null,<br>    next: null<br>  }<br>}</pre><p>Yeah hooks of a component is implementation of <strong>LinkedList.</strong></p><p>On mounting, an array of <strong>HookTypesDev </strong>created. It’s used to identify the order of hooks. Order is important, so there are <a href="https://reactjs.org/docs/hooks-rules.html"><strong>rules of hooks</strong></a> prevent you breaking its implementation.</p><pre>[&#39;useState&#39;, &#39;useState&#39;,...] // array of order hook types</pre><p>For example:</p><pre>function Counter () {<br>  const [count, setCount] = useState(0);<br>  const [anotherCount, setAnotherCount] = useState(0);<br>  const [check, setIsCheck] = useState(true);<br>  useEffect(()=&gt;{<br>   console.log(&quot;hello world&quot;)<br>  },[])<br>...</pre><pre>}</pre><pre>hooktypes will be<br>==&gt; [&#39;useState&#39;, &#39;useState&#39;, &#39;useState&#39;, &#39;useEffect&#39;]</pre><p>The idea <strong>mountHookTypesDev():</strong></p><pre>const hookName = ((currentHookNameInDev: any): HookType);    <br>if (hookTypesDev === null) {   <br>  hookTypesDev = [hookName];<br>} else { <br> hookTypesDev.push(hookName);  <br>}</pre><p>HookTypes is stored at <strong>_debugHookTypes </strong>property inside <strong>Fiber.</strong></p><pre>// Used to verify that the order of hooks does not change between renders.  <br>_debugHookTypes?: Array&lt;HookType&gt; | null,</pre><p>When running <strong>setCount</strong> to trigger updating, <strong>updateHookTypesDev() </strong>is<strong> </strong>called and it uses index to check whether the value<strong> “hookName” </strong>of<strong> HookTypesDev </strong>is equal to <strong>currentHookNameInDev</strong>. Guarantee the order of LinkedList hooks, so<strong> this approach help update the right hook.</strong></p><pre>const hookName = ((currentHookNameInDev: any): HookType); <br>if (hookTypesDev !== null) {      <br> hookTypesUpdateIndexDev++;      <br> if (hookTypesDev[hookTypesUpdateIndexDev] !== hookName) {  <br>   warnOnHookMismatchInDev(hookName);      <br> }<br>}</pre><p>After <strong>setCount</strong> to 1, the end result would be</p><pre>{<br>  memoizedState: 1, // our new state<br>  baseState: 1, // our new state<br>  queue: {<br>    last: {<br>      expirationTime: 1073741823,<br>      suspenseConfig: null,<br>      action: 1,<br>      eagerReducer: basicStateReducer(state, action),<br>      eagerState: 1, // our new state<br>      next: { /* ... */},<br>      priority: 98<br>    },<br>    dispatch: dispatchAction.bind(null, currentlyRenderingFiber, queue),<br>    lastRenderedReducer: basicStateReducer(state, action),<br>    lastRenderedState: 1, // our new state<br>  },<br>  baseUpdate: {<br>    expirationTime: 1073741823,<br>    suspenseConfig: null,<br>    action: 1,<br>    eagerReducer: basicStateReducer(state, action),<br>    eagerState: 1, // our new state<br>    next: { /* ... */},<br>    priority: 98<br>  },<br>  next: null,<br>}</pre><p>A lot has changed. The most significant being queue.last and baseUpdate. They contain information about the action just updated.</p><p>I won’t diving into any deeper, and stop here. My mission is to introduce to you the main basic idea how hook implemented. For more information, you can find it <a href="https://github.com/facebook/react/blob/27659559ebfd6b7119bfc0ff02ecb851c135020c/packages/react-reconciler/src/ReactFiberHooks.new.js">here</a>. Now let’s continue.</p><h3><strong>Why Asynchronous?</strong></h3><p>You probably know that updating state works asynchronously, which means the updated value is not presented immediately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBboHeM2mFtDTHiGSQkYJw.png" /></figure><p>For example, logging the count value right after the setCount call, return the old value 0, which we aren’t expecting. Sometimes i found newbies posting issues onto groups asking why their value still the same.</p><p>Because of <strong>Asynchronous.</strong></p><p>Let’s see why they design it that way.</p><h4><strong>1. Batching Update</strong></h4><p>When they design the API, the React team know that, in real world work, there are cases requiring us to trigger multiple updates at once. And Imagine how running the multiple update processes consecutively can lead to ugly performance issue. Render batching is when multiple calls to setState()/useState setterresult in a single render pass being queued and executed.</p><p>Let’s saying i press on my button, it increases <strong>count</strong> three times, we expect the end count value = 3. Unfortunately, because updating state works async, so the count value was equal 0 and it remains throughout the function, so no matter how many time <strong>setCount</strong> executes, the execution always is 0 + 1. That’s why count = 1. This is a case happening when you calculate based on previous state, be careful !</p><p>For the <strong><em>setIsCheck</em></strong><em>, it’s not calculating based on prevState, so it works like we expected, the end value is </em><strong><em>true.</em></strong></p><p>Still, it only queues <strong>one render pass ===&gt; </strong>batching update. You can test it by logging inside <strong>useEffect</strong></p><pre>const<em> </em>[<em>count</em>,<em> setCount</em>]<em> </em>=<em> useState</em>(0)<br>const<em> </em>[<em>isCheck</em>,<em> setIsCheck</em>]<em> </em>=<em> useState</em>(false)</pre><pre>const<em> onPress </em>=<em> </em>()<em> </em>=&gt;<em> </em>{<br> <em>setCount</em>(count<em> </em>+<em> </em>1) // 0+1<br> <em>setCount</em>(count<em> </em>+<em> </em>1) // 0+1<br> <em>setCount</em>(count<em> </em>+<em> </em>1) // 0+1</pre><pre><em>setIsCheck(true)<br>setIsCheck(false)<br>setIsCheck(true)</em></pre><pre>//evaluate to <br>this.setState({count: this.state.count +1})<br>this.setState({count: this.state.count +1})<br>this.setState({count: this.state.count +1})</pre><pre>//<em> the final result: count = 1, isCheck = true<br></em>}</pre><p>The API gives us access to the previous value of State, so we can calculate new value based on old value. This approach expose the value of state ahead of rendering process, and using the value to calculation is sweet.</p><pre>const<em> </em>[<em>count</em>,<em> setCount</em>]<em> </em>=<em> useState</em>(0)<br>const<em> </em>[<em>isCheck</em>,<em> setIsCheck</em>]<em> </em>=<em> useState</em>(false)</pre><pre>const<em> onPress </em>=<em> </em>()<em> </em>=&gt;<em> </em>{<br> <em>setCount</em>(prevCount =&gt; prevCount<em> </em>+<em> </em>1) // 0+1<br> <em>setCount</em>(prevCount =&gt; prevCount<em> </em>+<em> </em>1) // 1+1<br> <em>setCount</em>(prevCount =&gt; prevCount<em> </em>+<em> </em>1) // 2+1</pre><pre><em>setIsCheck(true)<br>setIsCheck(false)<br>setIsCheck(true)</em></pre><pre>//evaluate to <br>this.setState(prevState =&gt; {count: prevState.count +1})<br>this.setState(prevState =&gt; {count: prevState.count +1})<br>this.setState(prevState =&gt; {count: prevState.count +1})</pre><pre>//<em> the final result: count = 3, isCheck = true<br></em>}</pre><h4>Don’t break batch update</h4><p>It’s important to note that React will only batch updates that occurs in event handlers. This means that <strong>any state updates queued <em>outside</em> of the actual immediate call stack will <em>not</em> be batched together</strong>.</p><pre>const [counter, setCounter] = useState(0)<br><br>const onPress = async () =&gt; {<br>  setCount(0) <br>  setCount(1) // 1st render pass<br>  <br>  const data = await fetchSomeData()<br>  <br>  setCount(2) // 2nd render pass<br>  setCount(3) // 3rd render pass<br>}</pre><p>This will be 3 render passes.</p><p>The first render pass is a batch for <strong>setCount(0)</strong> and <strong>setCount(1)</strong> because they’re called in the same event handler</p><p>The second render pass happens for <strong>setCount(2)</strong>, because the synchronous of the original event has finished, and after <strong>await for fetchData</strong>, React begins a new call.</p><p>Then third render pass happens the same thing for <strong>setCount(3)</strong>, because it’s also running outside original event, so out batching</p><p>This case happens a lot, and not totally bad.Furthermore, I have seen lots of folks doing something like <strong>await this.setState() </strong>to wait for state update and get the current value, that breaks the batching feature as well. In other words, they unintentionally breaks batch update due to wait for the state value, and use it for the next calculation. This can be considering <strong>Handling Side Effect </strong>(we learn it in the next section).</p><h4>2. Guaranteeing Internal Consistency</h4><p>Even if state is updated synchronously, props are not. You can’t know props until you re-render the parent component, and if you do this synchronously, batching makes no good use.</p><p>==&gt; state, props, refs are internal consistent inside React, it’s easy to see how that is through usage in React core concepts.</p><p>Let’s saying we allow to update state synchronously. This works !</p><pre>console.log(count) // 0<br>setCount(count + 1)<br>console.log(count) // 1<br>setCount(count + 1)<br>console.log(count) // 2</pre><p>However, let’s say, one day other child components need to make use of count, so you have to refactor and <strong>lift state up</strong> to your parent component to share your state. This is common.</p><pre>props.onIncrement() // does the same thing - increase count + 1</pre><p>and this breaks</p><pre>console.log(props.count) // 0<br>props.onIncrement();<br>console.log(props.count) // 0<br>props.onIncrement();<br>console.log(props.count) // 0</pre><p>Because if state works synchronous, state is flushed immediately, but props.count is not. We can’t flush props immediately without re-rendering parent component, if we do so, it’s breaking batching.</p><h3><strong>Side Effects</strong></h3><p><strong>Side effects</strong> are effects/works happens after we have changed something or it’s not pure function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*pisDB4pcghiyrkfMNHKthA.jpeg" /></figure><p>Working with state is likely to always thinking about <strong>side effects.</strong></p><p>Asking yourself this question:</p><blockquote>After this state changed, what happens next?</blockquote><p>Does your text go from black to red?</p><p>Does your name go from Kush to Elsa?</p><p>Does you have to fetch another data based on new state?</p><p><strong>What gonna happen next bro?</strong></p><blockquote>A state changes lead to some other changes</blockquote><p>If your states change without any thing happens, you might not need to use state. Instead, you can use other variable kind to store your data, because it’s no need trigger a render pass.</p><p>Let’s saying i have a state storing the city name, and a Text display it. With that city name, i fetch data about streets in that city. So my city state is used for displaying and fetching data. I don’t want to split it into normal variable for fetch streets data, because i want <strong>single of truth</strong>. In this context, fetching data is a <strong>side effect</strong>, it happens every time i change city state.</p><p>React provides some ways to handle side effect happening according to state change, allow you to access fresh state value.</p><h4>Class component</h4><ol><li>The callback of setState:</li></ol><p>setState comes with a callback as 2nd argument. It’s a place we know our state is done updating. So we can access the fresh state value without committing any bad practice like await breaking batch update (mentioned above).</p><pre>this.setState(<br> { city: newCity },<br> ()=&gt; this.fetchStreets(this.state.city)<br>)</pre><p>2. <a href="https://reactjs.org/docs/react-component.html#componentdidupdate">componentDidUpdate():</a></p><p>This lifecycle can handle side effect as well. But be careful for infinite updating. Commonly have to use with comparison.</p><h4>Function Component</h4><ol><li>useEffect:</li></ol><p>useEffect with 2nd argument for array dependencies is great for handling all kind of side effects.</p><pre>const [city, setCity] = useState(&quot;&quot;)</pre><pre>useEffect(()=&gt;(<br>fetchStreets(city)<br>), [city])</pre><p>The effect happens every time the citychanges, including the first initial value of empty. I love this hook more than the class’s approaches, because i can code without worrying about forget to run fetchStreets() every time i change city, while approaches from class have to call it in the first rendering in componentDidMount() and manage later changing city. And it divide my logic into isolated blocks, easy to read, every effect relates to city assemble at one place.</p><p>Hook &amp; function component for better ^^</p><p>2. useLayoutEffect:</p><p>This is identical to useEffect, but it fires synchronously after all DOM/ShadowNodes mutations. Use this to read layout from the DOM/ShadowNodes and synchronously re-render.</p><p>useEffect is the recommended way.</p><h3>Placing your State</h3><p>Sometimes deciding where to put state is crucial to boost our performance. Inside a screen layout, with full of parent components, and child components. It’s not easy to decide the location for your state</p><p>So the question is:</p><blockquote>What factor decides the state position?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LBYVJuA1aP7U5Vr3BSu65A.png" /></figure><p>The only answer is the state’s purpose.</p><p>I mean, <strong>what will the state be used for?</strong></p><p>Is it used for only this component? Yes,<strong> Colocate State</strong></p><p>Is it used for many components (siblings/parents)? Yes, <strong>Lift State</strong></p><ul><li>Colocate State: Moving state to that specific component, remove the need of passing it around. An example when count only used by CounterComponent</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9Lk673Fg9Ght-HvSHikHA.png" /></figure><ul><li>Lift State: Moving state to <strong>the nearest parent</strong>. Then state can be used for parent/or pass down to child components via props. Ex: I added SlowComponent, both SlowComponent and CounterComponent use the same time state, so we lift up the state to <strong>their nearest parent</strong>, here is App</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xxpU5KxehI7zt8GzmvVUGw.png" /></figure><h3>How Colocate State Boosts Performance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*7gX__zqmdvqF_1ZEklqKwQ.png" /></figure><p>Let’s took an example, where i used props.time as a milisecond delay in SlowComponent via sleep() (Don’t mind my style lol ! just for quick)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F9Xr2VarZA7uWHFbZoU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Feducation-9Xr2VarZA7uWHFbZoU&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2F9Xr2VarZA7uWHFbZoU%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/3deadd878b0c8e7dee608e68bbd25bbf/href">https://medium.com/media/3deadd878b0c8e7dee608e68bbd25bbf/href</a></iframe><p>When i set the default time delay as 1000ms. Changing count state now affecting by the delay. The rendering is delayed withtime.</p><h4><strong>Why is that?</strong></h4><p>In my <a href="https://medium.com/javascript-in-plain-english/react-native-why-props-references-break-optimizations-79c463ca0723">previous post</a>, i described the rendering process. If you haven’t read, in brief, changing state inside a component, which marks that component as needing updated, queues a render pass and start at that component and loop downwards to its children to calculate the changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*DGVhUOMAjSHNsiNWR2A63w.png" /></figure><p>When we change count, it happens at the level of App component, then it triggers a rendering for child components (CounterComponent, SlowComponent). Because sleep() function delays the work of <strong>render phase</strong>, slow down the calculation of React → resulting in the <strong>commit phase</strong> is slow down too, it slows to commit the changes to the real UI tree, even CounterComponent has already done diffing its tree, it still has to wait for SlowComponent, because they commit at once.</p><h4>Colocate State to the rescue</h4><p>You can use <strong>React.useMemo</strong>, to skip the rendering of SlowComponent, so that when increase count, it doesn’t has to wait for SlowComponent</p><p>But we don’t want our code become ugly monsters every where. More elegant approach is to move count state inside CounterComponent, because SlowComponent don’t use it. And when changing count inside CounterComponent, React won’t care about SlowComponent, ignore diffing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*0M7yLKStDuhiGOZ1sSwfXg.png" /></figure><p>and the result is we can count extremely fast noww.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FJ4JgbuAzcBdJerVieV%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Feducation-J4JgbuAzcBdJerVieV&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FJ4JgbuAzcBdJerVieV%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="317" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c17483c68eec28dfa8e3cd32a6975d9/href">https://medium.com/media/5c17483c68eec28dfa8e3cd32a6975d9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*JUs58reRF4SVVABhUJwPDg.png" /></figure><p>In real work, there always happen cases like this. Putting your state wisely will help you avoid redundant heavy calculations. That’s why this is important !</p><p>An App Screen usually come with different UI sections/container. We don’t want rendering a small container triggers the whole screen to rendering, mind your state’s purpose, and place it properly to gain better performance.</p><h3>Summary</h3><p>In this post, to summary, we learned how to make good use of state:</p><ul><li>The reason why/when we need it</li><li>What role of state in big rendering picture ?</li><li>Important attributes like batching update, asynchronous,</li><li>Mental Model when writing state: thinking of side effects</li><li>Putting our state properly.</li></ul><p>Have a good day guys !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59721cbf0521" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-native-the-state-world-59721cbf0521">The most complete guide to React State you’ll ever read</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Props References Break Optimizations in React]]></title>
            <link>https://javascript.plainenglish.io/react-native-why-props-references-break-optimizations-79c463ca0723?source=rss-c853f5a06ee4------2</link>
            <guid isPermaLink="false">https://medium.com/p/79c463ca0723</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Kush Tran]]></dc:creator>
            <pubDate>Sat, 09 Jan 2021 15:19:16 GMT</pubDate>
            <atom:updated>2021-01-11T13:00:37.586Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Why Props References Break Optimizations in React + React Native</strong></h3><h4>Careful with props references when writing optimizations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNkiQfKMmhBIqfKSP0r69Q.jpeg" /></figure><p>React is great and fast most of the time. But sometimes, due to heavy calculations, it slows down, that’s when we need to measure and optimize our Components to avoid “wasted renders”.</p><p>Optimizations come with its cost, if it’s not done properly, the situation might get worse. In today’s blog post, we get to know the rendering process, learn the cause of wasted renders, solutions &amp; how it’s broken.</p><h4>Table of contents</h4><ul><li><strong>What is “Rendering” ?:</strong> Process Overview, Render &amp; Commit Phase</li><li><strong>Standard Render Behavior: </strong>The cause of wasted renders in Render Phase</li><li><strong>Improving Rendering Performance: </strong>Some techniques</li><li><strong>How New Props References break Optimizations: </strong>The detail of the problem</li><li><strong>Optimizing Props References: </strong>useMemo &amp; useCallback</li><li><strong>Memoize Everything?</strong></li></ul><h3>What is “Rendering” ?</h3><p><strong>Rendering</strong> is the process of React asking your Components to describe what the section UI looks like, on the current combination of Props and State.</p><h4>Process Overview</h4><p>During the process, React will start at the root of the component tree and loop downwards to find the components flagged as needing updates. For each flagged components, it will call<strong> render()</strong>(for class components) or <strong>FunctionComponent()</strong>(for function components), and save the render outputs.</p><p>A component render’s output is written in <strong>JSX</strong>. Either from <strong>render()</strong> or <strong>FunctionComponent()</strong>, the output eventually becomes <strong>ReactElement</strong>. These elements are used together to form the virtual tree (tempt tree).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-5em1cnHXile0O-yzytGw.png" /></figure><p>After collecting the new tree, React will diff it, collect lists of all changes need to be applied to make the real tree look like the current desired output. This process is called <a href="https://reactjs.org/docs/reconciliation.html"><strong>Reconciliation</strong></a>.</p><p>Above is very basic process to create <strong>Host tree</strong> (the tree output). The host tree can be vary of types, base on different platforms (web, mobile,…). Dan Abramov wrote a great explanation for it <a href="https://overreacted.io/react-as-a-ui-runtime/"><strong>Here</strong></a><strong>.</strong></p><p>React team divides above work into 2 phases:</p><ul><li>The “<strong>Render phase</strong>” contains all the work of rendering components and calculating changes.</li><li>The “<strong>Commit phase</strong>” is the process of applying those changes to the host tree.</li></ul><h3>More layers for React Native (You can skip this and move on if you’re not interested)</h3><p>React Native creates a tree hierarchy to define the initial layout and creates a diff of that tree on each layout change like above. Except React Native manages the UI updates through couple of architecture layers that in the end translate how views should be rendered.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8va9prUqjnA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8va9prUqjnA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8va9prUqjnA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6244531bc5e6df01aec2106b4e57026e/href">https://medium.com/media/6244531bc5e6df01aec2106b4e57026e/href</a></iframe><h4>1. The Yoga layout engine</h4><p><a href="https://github.com/facebook/yoga">Yoga</a> is a cross-platform layout engine written in C which implements Flexbox through bindings to the native views <em>(Java Android Views / Objective-C iOS UIKit)</em>.</p><p>All the layout calculations of the various views, texts and images in React-Native are done through yoga, this is basically the last step before our views get displayed on the screen</p><h4>2. Shadow tree/Shadow nodes</h4><p>When react-native sends the commands to render the layout, a group of shadow nodes are assembled to build shadow tree which represented the mutable native side of the layout (i.e: written in the corresponding native respective language, Java for Android and Objective-C for iOS) which is then translated to the actual views on screen (using Yoga).</p><h4>3. ViewManager</h4><p>The ViewManger is an interface that knows how to translate the View Types sent from the JavaScript into their native UI components. The ViewManager knows how to create a shadow node, a native view node and to update the views. In the React-Native framework, there are a lot of ViewManager that enable the usage of the native components. If for example, you’d someday like to create a new custom view and add it to react-native, that view will have to implement the ViewManager interface</p><h4>4. UIManager</h4><p>The UIManager is the final piece of the puzzle, or actually the first. The JavaScript JSX declarative commands are sent to the native as Imperative commands that tell React-Native how to layout the views, step by step iteratively. So as a first render, the UIManager will dispatch the command to create the necessary views and will continue to send the update diffs as the UI of the app changes over time.</p><p>So React-Native basically still uses React’s ability to calculate The difference between the previous and the current rendering representation and dispatches the events to the UIManager accordingly.</p><h3><strong>Standard Render Behavior</strong></h3><p>It is important that:</p><p><strong>React’s default behavior is that when a parent component renders, React will recursively render <em>all</em> child components inside of it!</strong></p><p>For example, say we have a component tree of <strong>A &gt; B &gt; C.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YysWA8NaJ1LUUGQ1yP5hg.png" /></figure><ul><li>We trigger a re-render in<strong> B </strong>(<strong>setState</strong> or <strong>setter of useState</strong>).</li><li>React starts the render pass from the top of the tree</li><li>React sees that <strong>A </strong>is not marked as needing an update, and past it</li><li>React sees that <strong>B </strong>is marked as needing an update, and renders it. <strong>B</strong> returns <strong>&lt;C /&gt;</strong> as it did last time.</li><li><strong>C</strong> was <em>not</em> originally marked as needing an update. However, because its parent<strong> B</strong> rendered, React now moves downwards and renders <strong>C</strong> as well.</li></ul><p>Now, it’s likely that most of the components will return the exact render result as last time, therefore, React won’t need to make change to the real tree. However, React will still have to ask the components re-render themselves and diff the render output. Both of those take time and effort, especially when the components are large &amp; have heavy calculations.</p><p>This is how wasted renders happens.</p><h3><strong>Improving Rendering Performance</strong></h3><p>Renders are normal expected part of React. It’s also true that sometimes the effort is wasted if a component’s render output hasn’t changed, and that part of the tree doesn’t need updating.</p><p>Render should always based on current<strong> Props and State </strong>of component. If we know ahead of time that Props and State won’t change. the render output won’t change, then we can safely skip the rendering process of that component.</p><p>When it comes to optimization, you can make it run faster or do less work. Most of React optimization is about doing less work.</p><blockquote>Remember to measure before any optimization, so you don’t commit premature optimization.</blockquote><p>React offers three primary APIs for skipping rendering of a component.</p><ul><li><a href="https://reactjs.org/docs/react-component.html#shouldcomponentupdate"><strong>React.Component.shouldComponentUpdate</strong></a><strong>: </strong>A component lifecycle happens early in the render process. (happening in updating lifecycle). If return <strong>false</strong>, React will skip rendering component. By default, it always return <strong>true</strong>, so when you need to skip rendering component, you can add your own logic. Commonly, when we custom this lifecycle, we compare the old props, state with the new ones, and return <strong>false</strong> if nothing change.</li><li><a href="https://reactjs.org/docs/react-api.html#reactpurecomponent"><strong>React.PureComponent:</strong></a><strong> </strong>Since the comparison of props and state is the most common way to implement <strong><em>shouldComponentUpdate. PureComponent </em></strong>is a base class implements that behavior by default. Can be used instead of<strong> React.Component + shouldComponentUpdate.</strong></li><li><a href="https://reactjs.org/docs/react-api.html#reactmemo"><strong>React.memo</strong></a><strong>: </strong>A built-in <a href="https://reactjs.org/docs/higher-order-components.html"><strong>higher order component</strong></a><strong>. </strong>It accepts your component and return a new wrapper component. Wrapper component’s default behavior is to check if any props has changed, if not, it prevents rendering. It also accept your custom logic for the comparison work, commonly this is used to compare specific props, instead of all of them.</li></ul><p>All of these approaches use a comparison technique called<em> Shallow Equality</em>. This means checking individual field in two different objects, and seeing if any difference in the contents of objects. The technique compares with <strong>===</strong>, a simple and fast way JS engine can do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_auVS8CZsalet-Ku-feZQ.png" /></figure><h3><strong>How New Props References break Optimizations</strong></h3><p>As we learned about techniques with <strong>shallow equality </strong>above, it’s apparent that passing new objects will fail the comparison because “===” compares <strong>reference</strong>, even if the contents haven’t changed. That breaks our optimizations, the component still renders, but <strong>wasting more diffing effort,</strong> diffing through props comparison &amp; diffing tree. Be careful !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK9-_GaHJ6XfHgBfJNnzgQ.png" /></figure><p>In the example, we pass <strong>onClick</strong> and <strong>data </strong>as props to <strong>MemoizedChildComponent</strong>. Although we optimize ChildComponent, it still re-render every ParentComponent updating. Because <strong>MemoizedChildComponent’s props get new objects every time.</strong></p><p>We expect <strong>MemoizedChildComponent </strong>skip rendering because it’s props contents are the same. Let’s move on and figure how we can fix this.</p><h3>Optimizing Props References</h3><p>Class components don’t have to worry about accidentally creating new callback object references as much, because they can have instance methods that are always the same reference. However, they may need to generate unique callbacks for separate child list items, or capture a value in an anonymous function and pass that to a child. Which resulting in new objects, React hasn’t come with any built-in to optimize those cases.</p><p>Function component, React offer two hooks <a href="https://reactjs.org/docs/hooks-reference.html#usecallback"><strong>useCallback</strong></a> (for callback function) and <a href="https://reactjs.org/docs/hooks-reference.html#usememo"><strong>useMemo</strong></a>(for any kind of data like creating objects or complex calculations).</p><blockquote>The intention of this post is to draw the problem out, not teaching about Hook, i believe there are many sources explaining those Hook well. So i’m not going into detail here. Maybe in the next posts, who knows right ^^</blockquote><h3><strong>Memoize Everything?</strong></h3><p>Apparently <strong>NO</strong>, every optimization comes with its cost. Optimizing carelessly ends up making the performance worse, always measure first, by React devtool or any of your favorite, find the bottleneck, and then optimize.</p><p>It’s not always benefit, if it was, React would make it the default implementation, right ? :D</p><p>Kent C. Dodds mentioned a case when <strong>useCallback</strong> worse <a href="https://kentcdodds.com/blog/usememo-and-usecallback">here</a>. And my favorite Dan’s tweet:</p><blockquote>Why doesn’t React put memo() around every component by default? Isn’t it faster? Should we make a benchmark to check? Ask yourself: Why don’t you put Lodash memoize() around every function? Wouldn’t that make all functions faster? Do we need a benchmark for this? Why not?</blockquote><h3><strong>Summary</strong></h3><p>Well, that’s the end of this post.</p><p>To summary, Rendering process of React renders children components due to updating parent components, that’s not bad, that’s how React knows the changes. And sometimes the rendering effort is wasted.</p><p>Skipping rendering is a common way to optimize this, and the work relates to <strong>props references</strong> a lot. Optimizing with care, don’t premature optimization.</p><p>Props Reference has more problems than that. Recently, i love Ben’s <a href="https://t.co/ysL6qYw1KW"><strong>article</strong></a> on how it affects dependencies in useEffect hook.</p><p>For any further questions or comments, let me know. Thanks !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c463ca0723" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-native-why-props-references-break-optimizations-79c463ca0723">Why Props References Break Optimizations in React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>