<?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 Jasbindar Singh on Medium]]></title>
        <description><![CDATA[Stories by Jasbindar Singh on Medium]]></description>
        <link>https://medium.com/@jasbindar1998?source=rss-188f8faf6bb8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Uv2ALzsA8Yw9C_9es5MyiQ.jpeg</url>
            <title>Stories by Jasbindar Singh on Medium</title>
            <link>https://medium.com/@jasbindar1998?source=rss-188f8faf6bb8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:05:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasbindar1998/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[Exploring React Renders]]></title>
            <link>https://medium.com/better-programming/exploring-react-renders-aa20b71296fe?source=rss-188f8faf6bb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa20b71296fe</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Jasbindar Singh]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 00:05:08 GMT</pubDate>
            <atom:updated>2020-07-24T00:05:08.710Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimization and performance improvement using memo, useCallback, and useMemo</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UP76AGILWtS7H2ru" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog post, we will be looking at different scenarios/cases on how to optimize React components and avoiding unwanted renders using some features that React provides, i.e. memo, useCallback, and useMemo. This is not meant to be an introductory post so, some prior knowledge of React is a prerequisite.</p><h3>Introduction</h3><p>React triggers the render method in specific cases, such as state modification and props change, but there are different scenarios where it re-renders components when writing a specific code. These re-renders are unexpected and usually ignored by someone who has just started with React, and it is really important to know what causes and how to avoid these re-renders. I have already written about different re-render scenarios that may cause a performance bump.</p><p>In this post, we would see how we can use different methods in different scenarios to avoid the re-render of components when using React.</p><h3>Scenarios to Understand</h3><h4>Passing Props</h4><p>In React, child components can have props passed down to them from their parent component, we can pass down any number of values as props to the child. So, when the values passed down as props changes, the child component re-renders, and it should keep the view updated. But what if we do not pass a prop or if the props passed do not change, would the child component re-render in that case too?</p><p>Yes, it will, and that might hit your performance on a larger scale application. Now, let’s see how we can optimize it using the memo method that React provides. Here is an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75cf6d730c480e1c65630252c75dfc3e/href">https://medium.com/media/75cf6d730c480e1c65630252c75dfc3e/href</a></iframe><p>In the above example, if the Increment button is clicked, it will cause a state update, which would trigger a component re-render. So, the ParentComponent gets re-rendered, but what about its children. Here, we have three children in the ParentComponent, ChildComponent1 with no props passed, ChildComponent2 with props passed that will change on Increment button clicks, andChildComponent3 with props passed that will not change. So, when the button is clicked, all of them get rendered even though one did not have any props passed and the other one had unchanged props. This could create a problem when using comparatively bigger components or nested components and that would cause unnecessary renders. To prevent this, React has a higher-order component, i.e memo().</p><h4>Memo()</h4><p>memo() creates a memoized version of your React component and whenever a new render triggers, it compares the prop passed to it with the previous props, if they are same then the render is skipped, and if different a render is triggered. You can use it on both class components and functional components, but you already have PureComponent defined for class-based components usage, it basically serves the same purpose as memo() for class components. While using memo() you can still have state and context on your component that would work as expected.</p><p>Now, let us replace the three child components from the previous example with the new ones using memo():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c65a9b592af10dd4d77ced33e02c694/href">https://medium.com/media/5c65a9b592af10dd4d77ced33e02c694/href</a></iframe><p>Now, let us check the console in the browser, you will notice that the increment button’s clicks no longer render the ChildComponent1 and ChildComponent3 components. This is where the memo() method comes in handy when passing down props to components.</p><p>So, now we know how to optimize our code when passing down props to, but was it enough to cover all the cases?</p><h4>Passing references</h4><p>In the previous code snippet, we were passing state counter value as props, we know values are of different types and not all of them behave in the same way. For example, comparing two numbers is not the same as comparing two objects because numbers would be compared by their values but objects are compared with their reference in the memory. 5 === 5 returns true, but {a: 5}==={a: 5} returns false.</p><p>Let us look at an example for a better understanding:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aef84ba3936f587c9720953cbe88a451/href">https://medium.com/media/aef84ba3936f587c9720953cbe88a451/href</a></iframe><p>In the above example, we are passing the state counter to the first child component Child1 and a function to the second child component Child2. Here we have used the memo() HOC (explained above) to optimize this example and avoid unnecessary Child2 re-renders. Now, let us click on the Increment button and check if the Child2 component is re-rendering or not. Did it re-render?</p><p>Yes, it is still re-rendering despite using the memo() HOC, this was not what we were expecting. So, let us break down the code and try to understand what caused this.</p><p>We used the memo() HOC on the Child2 component, so we have a memoized version of the component that would only change if the props passed are changed, but the props passed is just a static function, so how does it change? It changes every time the Parent component is re-rendered. When passing a function as a prop we pass its reference, so with every re-render, the function gets re-created in the memory in a different memory location, i.e. reference, and hence memo() gets new a reference every time to compare and thus results in a re-render. Now, that we know the reason for the renders how do we solve this?</p><p>Note: This occurs only when using a functional component because a class component does not re-create functions defined in it on every render it just calls its render method.</p><p>The React team was aware that defining a function inside a functional component would give rise to this issue. So, they came up with a solution for the issue, i.e the useCallback hook.</p><h4>useCallback hook</h4><p>useCallback is somewhat similar to the memo() HOC. The useCallback hook creates a memoized version of the function with the presence of a dependency array, the function only gets re-created if any of the values in the dependency array changes, so if a parameter used in the callback modifies the end result returned then it adds that parameter to the dependency array if the array is left empty and the function would not be re-created again.</p><p>So, let’s use this hook and pass a new memoized function to solve the re-rendering issue. This time, we should ignore the memoizedFunction function, and instead use the handleEvent function for the Child2 component.</p><p>const memoizedFunction = useCallback(handleEvent, [])</p><p>Now, we have fixed the issue of re-rendering when passing references as props using memo and useCallback</p><h4>Using Context API</h4><p>When using context we have to be careful with what we pass down as values because one modification and the whole tree structure of components in the Provider tag would re-render. So to prevent this, it is always advisable to use memo on all the components under the Provider tag. That way you would be saved from unknown renders to propagate the whole tree. If passing a function down as context, do remember to use the useCallback hook and for functions that take a significant amount of time to return data, we can use the useMemo hook. Now let’s look at what theuseMemo hook does.</p><h4>useMemo hook</h4><p>We covered the memo() HOC and the useCallback hook for optimization, now let us look at the useMemohook which is also used for optimization. The useMemo hook is similar to the useCallback hook, both follow the same principle of memoization, the only difference between them is that the useCallback hook memoizes the function whereas the useMemo hook memoizes the data return by the function. There are certain cases when you have utility functions that return a data/ a set of data in a significant amount of time, so, you would not want that function to run every time your component gets re-rendered. You would only want it to run when it returns a new set of data. This hook also takes in two arguments, the first one being the callback and the second is a dependency array. Let’s see an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ae3f45cba90e9f56790c134a7358abc/href">https://medium.com/media/5ae3f45cba90e9f56790c134a7358abc/href</a></iframe><p>In this example, every time you click the Increment button and modify the state, the parent component re-renders, and the heavyComputationFunction function is also going to be re-created and re-run every time state changes while returning the same data. This could have a bump on performance. You would only want the function to run if it returned a new value and this is where useMemo comes in handy. The useMemo hook takes a callback and a dependency array and memoizes the value returned in the first function run, now, it will only re-run and re-compute again if any value in the dependency array changes. So, in the above example just replace line number 9 with:</p><p>const message = useMemo(heavyComputationFunction, []);</p><p>Now, the function heavyComputationFunctionis not called every time the components get re-rendered, because the value is memoized.</p><h3>Conclusion</h3><p>Congratulations on reaching this far in the article. But if you are considering to use memo(), useCallback, and useMemo all over your app structure, whether it’s required or not, because using them will make your web app faster, better, and without side effects…</p><p>I should stop you right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*3IteaeR4E_9gZz9FSclayg.gif" /><figcaption>Source: giphy.com</figcaption></figure><p>Using these methods everywhere would be a terrible idea. You should always consider that using these methods, memoizing data and comparisons, will also require time and computational power. Sometimes it is better not to use these methods until your web app starts to feel slow/sluggish. These methods are great but they have side effects too. If you want to know more about their side effects and comparisons, here is a post that is worth reading:</p><p><a href="https://kentcdodds.com/blog/usememo-and-usecallback">When to useMemo and useCallback</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa20b71296fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/exploring-react-renders-aa20b71296fe">Exploring React Renders</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring React Renders: Different ways a component gets re-rendered.]]></title>
            <link>https://medium.com/bitsrc/exploring-react-renders-different-ways-a-component-gets-re-rendered-edc11403b754?source=rss-188f8faf6bb8------2</link>
            <guid isPermaLink="false">https://medium.com/p/edc11403b754</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jasbindar Singh]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 17:09:45 GMT</pubDate>
            <atom:updated>2020-06-24T07:21:50.612Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring React Renders: Different Ways a Component Gets Re-Rendered.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gttkvGp24YhMvFPb1RnCZA.png" /></figure><p>In this blog post, we would be looking at different scenarios/cases on how React components render and re-renders. This is not to be an introductory post so, some prior knowledge of React would be a prerequisite.</p><h3>What is a render?</h3><blockquote>Render, it is the process of generating a final product output from a specific type of input.</blockquote><p>In React, render is the process of converting the JSX that you write into the DOM nodes, if the node is already present it updates the nodes according to the new data. So, what’s the problem with renders?</p><p>There is no specific problem with rendering a component, but if that component becomes too big or nested on several levels it can hit you up in performance. So, what happens when a component re-renders frequently or unexpectedly?</p><p>When a component is re-rendered the JSX is written again to the DOM which takes extra computation power and time. But this is where React’s VDOM comes into the picture, the JSX you write is painted on the VDOM first and then a diffing algorithm is used to compare the new VDOM to the old VDOM and if some changes are found, those are then pushed to the browser DOM, that is called reconciliation, and then the required changes and updates are pushed to DOM instead of rendering the whole component.</p><p>So, now when we know what a render is and how it can affect performance, let us see what are different ways that can cause these renders.</p><h3>What causes a render in react?</h3><ul><li>State modification</li><li>Passing props</li><li>Using the Context API</li><li>Passing references(array, function, and object)</li></ul><p>Let us see all the scenarios one by one,</p><h4>State modification</h4><p>Component re-renders when its state is manipulated, simple as that. So, when you modify the state of your component it tends to re-renders with the new state value. Let us check with an example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a267d8d1698be9e4c35b3b1b177ad41d/href">https://medium.com/media/a267d8d1698be9e4c35b3b1b177ad41d/href</a></iframe><p>When running this snippet, go to the console from developer tools and observe that every time you click the increment button it will modify the state, and thus the component would re-render i.e. you see the “App Rendered!” logs. (Note: If you see the logs statement twice on every click don’t worry, refer to the end of the blog section #Anomaly Render). If the component has any child components or nested hierarchical components, all of them would get rerendered.</p><p>So, how does setCounter works? The answer is, it compares the new state passed with the previous one and if they are different it will trigger a render. Now, if the new state is equal to the previous one, it will not trigger a render. So, when you change line number 11 in the above snippet to setCounter(0), you would see the component doesn’t get rerendered on further button clicks anymore, because the new value is the same as the previous one.</p><p>Note for a class component: The same thing if you do for a class component you would notice that it re-render the component every time if you change the state whether with the same previous value or a new value, to overcome this and control renders you would have to override the shouldComponentUpdate lifecycle method.</p><h4>Passing Props</h4><p>Coming to props, if the parent component has triggered a rerender all the child component will rerender too, generally you would only want the specific child components to rerender only if the component is consuming some props or the passed props are modified but that isn’t the case, it does not matter if the props are consumed, modified or not, the child components will re-render if the parent component has triggered a render. Here is an example to understand it better,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75cf6d730c480e1c65630252c75dfc3e/href">https://medium.com/media/75cf6d730c480e1c65630252c75dfc3e/href</a></iframe><p>Click on the increment button, and the state counter changes. Now you would notice that not only the parent component re-render but also all the child component re-renders too, ChildComponent1- the one without the prop, ChildComponent2- the one with changing prop and ChildComponent3- the one with the unchanged prop. This is unexpected because the first child is not associated with any props and the third child is associated with a prop that is unchanged, still, both of them get rerendered with the parent and the second child component. This should not be the case, but this is how React’s render works.</p><h4>Using the Context API</h4><p>React introduced the Context API to ease the data flow from Parent component to inner hierarchical child components at any level of nesting, you create a data context provider at the root component and can consume the data in any of its nested hierarchical child components. Context API with the addition of the new useContext hook becomes an easy and intuitive way to pass down values. But, when using Context API we should also see what causes it’s child components to render. Let us understand with an example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e8476e7f00c12ee0850bed249fd02e/href">https://medium.com/media/02e8476e7f00c12ee0850bed249fd02e/href</a></iframe><p>In this example, we have created a data context, we are also passing down the state counter data to the provider. Now, any child component under the provider tag can consume the data, one of the preferred ways would be to use the useContext hook. When modifying the state which is also the value passed to the context we will observe that the whole child components tree would get rerendered. Again doesn’t matter if the child component is consuming the context data or not, it will still rerender. The rerenders depend on the value passed to the provider but still, all the whole components tree would get rerendered.</p><h4>Passing down references</h4><p>Before diving further first let us see some of the JavaScript equality comparisons,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69b1cc259fa1ba0b75cb9c6aaa5a8ce2/href">https://medium.com/media/69b1cc259fa1ba0b75cb9c6aaa5a8ce2/href</a></iframe><p>So, here we can see that the objects are compared using their references, and the other comparison is based on their values and they yield true when compared but in case of an object, array and, function comparison is based on references i.e. the exact memory location so, their comparison even though they seem equal yields false, in React Object.is method is used to compare the different values. To understand how does this affect our react application let us look at an example,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/146a6531f57b8b23317b5617f1aafd48/href">https://medium.com/media/146a6531f57b8b23317b5617f1aafd48/href</a></iframe><p>Do you think that in the above example the ParentComponent component would get rendered, when the button is pressed?</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>Yes, it will.</p><p>Because when comparing the previous state to the new state, it returns false because they do not have the same reference, these comparisons would result in the same when using arrays or function. So, when handling objects, functions, arrays as your state, context, or passing props, we have to be careful cause these would create unexpected renders.</p><h3>Extra: Anomaly Render</h3><p>So, people coming from the first example confused why their component is getting rendered twice, the reason is that this happens because of React’s strict mode, just go to the index.js file and remove the React.StrictMode tag, this should solve your problem. You can also run the development build to cross-check, it will act normal with one log statement on the console per click.</p><p><a href="https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/">My React components render twice and drive me crazy</a></p><h3>Conclusion</h3><p>So, this was how you can create rerenders in different ways, that can be avoided. The scenarios mentioned above will be useful when considering the performance of the app, now you would know why your components are getting rendered unexpectedly. Though render is not the only thing that makes your app perform better, but it could be one of the causes that can make it slow.</p><p>In this part, we created different render scenarios, on the coming blog we would see how to solve/optimize these re-renders using different methods and features that React provides.</p><p>Thanks for reaching this far and completing the post, I hope you got some of your React render questions answered. If you have any doubts or questions regarding this topic, feel free to comment your thoughts below.</p><p>If you liked this post, please leave some claps it helps to stay motivated to write more such posts.</p><h3>Publish and Reuse React Components with Bit</h3><p><a href="https://bit.dev/">Bit</a> makes it easy to publish reusable React components from any project to Bit’s component hub.</p><p><strong>Need to update a published component? </strong>bit import it into your project, change it, and push it back with a bumped version.</p><p><a href="https://bit.dev/">Share components</a> with your team to maximize code reuse, speed up delivery and build apps that scale.</p><figure><a href="https://bit.dev/"><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ptx4tj9cJ2i2gxMM.gif" /></a><figcaption>Example: exploring React components published on <a href="https://bit.dev/">Bit.dev</a></figcaption></figure><h3>Related Stories</h3><ul><li><a href="https://blog.bitsrc.io/theming-react-components-with-css-variables-ee52d1bb3d90">Theming React Components with CSS Variables</a></li><li><a href="https://blog.bitsrc.io/how-to-publish-react-components-d04e0a7e33b9">How to Publish React Components</a></li><li><a href="https://blog.bitsrc.io/13-top-react-component-libraries-for-2020-488cc810ca49">13 Top React Component Libraries for 2020</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edc11403b754" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/exploring-react-renders-different-ways-a-component-gets-re-rendered-edc11403b754">Exploring React Renders: Different ways a component gets re-rendered.</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>