<?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 Rohit Kumawat on Medium]]></title>
        <description><![CDATA[Stories by Rohit Kumawat on Medium]]></description>
        <link>https://medium.com/@geekrk.01?source=rss-24ad10513560------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*S9xt3NTAbiHypz3E.</url>
            <title>Stories by Rohit Kumawat on Medium</title>
            <link>https://medium.com/@geekrk.01?source=rss-24ad10513560------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:44:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@geekrk.01/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[Peformance optimization in React using shouldComponentUpdate()]]></title>
            <link>https://medium.com/@geekrk.01/peformance-optimization-in-react-using-shouldcomponentupdate-30ad5b2a03cc?source=rss-24ad10513560------2</link>
            <guid isPermaLink="false">https://medium.com/p/30ad5b2a03cc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[shouldcomponentupdate]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rohit Kumawat]]></dc:creator>
            <pubDate>Fri, 21 Aug 2020 05:42:59 GMT</pubDate>
            <atom:updated>2020-08-21T12:06:20.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance optimization in react using shouldComponentUpdate()</h3><p>There are many performance optimization concepts in react which helps us to build faster applications.</p><p>Today I am going to discuss one of most discussed concept in performance optimization: <strong>how to avoid Reconciliation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*PLFS3imAGzAWKkoU79e9QQ.png" /></figure><h3><strong>What is Reconciliation?</strong></h3><ol><li>React maintains the internal representation of UI by creating a tree like structure of every DOM object in memory which is called Virtual DOM.</li></ol><p>Basically it is just a javascript object which keeps information of every DOM object. Imagine virtual DOM as a javascript object which keeps information about every element.</p><pre>{<br>    node: &#39;html&#39;,<br>    properties: {<br>        attributes: [],<br>        classes: [],<br>        events: []<br>    },<br>    children: {<br>        node: &#39;body&#39;<br>        properties: {<br>            attributes: [],<br>            classes: [],<br>            events: []<br>        },<br>        children: [<br>            {        <br>                node: &#39;div&#39;,<br>                properties: {<br>                    attributes: [],<br>                    classes: [],<br>                    events: []<br>                },</pre><pre>},<br>            {<br>                node: &#39;button&#39;,<br>                properties: {<br>                    attributes: [],<br>                    classes: [],<br>                    events: []<br>                }<br>            }<br>        ]<br>    }<br>}</pre><p>2. Whenever we update the state or props changes: Component returns the elements.</p><p>Then, React compares the newly returned elements with the previously rendered ones by comparing `virtual DOM` snapshot of new object with last updated object. This way React has to update only changed nodes in React DOM.</p><blockquote>This whole process is how React updates DOM which is called Reconciliation.<br>This process is way faster than Real DOM manipulation.</blockquote><blockquote>Even though React is clever enough to update only changed nodes. But when props and state changes, re-rendering takes place which takes some time.</blockquote><blockquote>So we need to avoid unnecessary re-rendering for such cases.</blockquote><p><strong>The Case where we need to avoid Reconciliation or stop the re-rendering process:</strong></p><p>When parent component renders, all its child components are re-rendered even if their props or states didn’t change.<br>And if child component contains a very slow computation then, it will be computed in every re-render.</p><p><strong>[Our Case]</strong></p><p><strong>The parent component contains:</strong></p><ul><li>A Button element which changes the counter value.</li><li>A child component which is dependent of parent prop called `color` which is changed by selecting a color from select element.</li></ul><p><strong>In child component:</strong></p><ul><li>There is a delay function which replicates a time taking computation.</li></ul><blockquote>Even if you change the counter value using button element in Parent, the child component re-renders hence the computation along with it takes place which is quite noticable in example below.</blockquote><ol><li>Parent Component:</li></ol><pre>import React from &#39;react&#39;;<br>import Child from &#39;./Child&#39;;</pre><pre>class Parent extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      counter: 0,<br>      color: &#39;red&#39;<br>    }<br>  }</pre><pre>render() {<br>    console.log(&#39;[Parent] rendered&#39;);</pre><pre>return (<br>      &lt;div className=&quot;container&quot;&gt;<br>          &lt;div&gt;Counter:  {this.state.counter}&lt;/div&gt;</pre><pre>&lt;button onClick={() =&gt; this.setState({counter: this.state.counter + 1})}&gt;Click me to change counter&lt;/button&gt;</pre><pre>&lt;select defaultValue=&quot;red&quot; onChange={(e) =&gt; this.setState({color: e.target.value})}&gt;<br>            &lt;option value=&quot;red&quot;&gt;red&lt;/option&gt;<br>            &lt;option value=&quot;blue&quot;&gt;blue&lt;/option&gt;<br>            &lt;option value=&quot;grey&quot;&gt;grey&lt;/option&gt;<br>          &lt;/select&gt;</pre><pre>&lt;Child color={this.state.color} /&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><pre>export default Parent;</pre><p>2. Child Component:</p><pre>import React from &#39;react&#39;;</pre><pre>class Child extends React.Component {<br>    delay() {<br>        console.log(&#39;[Delay] function called&#39;);</pre><pre>for(let i = 0; i &lt; 5000000000; i++) {<br>            i++;<br>        }<br>        return &#39;delayed text&#39;;<br>    }</pre><pre>render() {<br>        console.log(&#39;[Child] rendered&#39;);</pre><pre>return (<br>            &lt;div className=&quot;child&quot;&gt;<br>                &lt;hr /&gt;<br>                &lt;div&gt;{this.delay()}&lt;/div&gt;<br>                Selected Color: {this.props.color}<br>            &lt;/div&gt;<br>        )<br>    }<br>}</pre><pre>export default Child;</pre><p>That’s where <strong><em>shouldComponentUpdate()</em></strong> comes in. It is the lifecycle method which is called before re-rendering starts in class based components.</p><h3><strong>1. How shouldComponentUpdate() works:</strong></h3><pre>shouldComponentUpdate(nextProps, nextState)</pre><ul><li>Invoked before re-rendering.</li><li>It receives updated prop object and state.</li><li>Returns `true` by default which means component will re-render by default.</li><li>We can compare previous prop and state changes with nextProps and nextState respectively and return false if we don’t want to re-render.</li><li>If we retun false then UNSAFE_componentWillUpdate(), render(), and componentDidUpdate() will not be invoked — Hence no re-rendering.</li><li>This lifecycle method can be skipped when used forceUpdate().</li></ul><p>Example:</p><pre>/* Assume props = {color: &#39;red&#39;} state={counter: 0} */</pre><pre>class Parent extends React.Component {<br>shouldComponentUpdate(nextProps, nextState) {<br>  if(this.nextProps.color === this.props.color) {<br>    return false;<br>  }<br>  if(this.nextState.counter === this.state.counter) {<br>    return false;<br>  }<br>  return true;<br>}</pre><blockquote>So, if the color prop and counter variable in state doesn’t change then this component won’t re-render.</blockquote><h4>Optimizing performance of above example:</h4><p>Now we use shouldComponentUpdate() to compare the props and return false if props doesn’t changes.</p><p><em>Child Component with shouldComponentUpdate:</em></p><pre>import React from &quot;react&quot;;</pre><pre>class Child extends React.Component {<br>  delay() {<br>    console.log(&quot;[Delay] function called&quot;);</pre><pre>for (let i = 0; i &lt; 800000000; i++) {<br>      i++;<br>    }<br>    return &quot;delayed text&quot;;<br>  }</pre><pre>shouldComponentUpdate(nextProps, nextState) {<br>    if (this.props.color === nextProps.color) {<br>      return false;<br>    } else {<br>      return true;<br>    }<br>  }</pre><pre>render() {<br>    console.log(&quot;[Child] rendered&quot;);</pre><pre>return (<br>      &lt;div className=&quot;child&quot;&gt;<br>        &lt;hr /&gt;<br>        &lt;div&gt;{this.delay()}&lt;/div&gt;<br>        Selected Color: {this.props.color}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Child;</pre><h4><strong>Live Examples:</strong></h4><p>I have added the codesandbox urls below for both state of application before optimization and after optimization with shouldComponentUpdate().</p><p>In the example I have also added consoles so that we can observe which component are rendered and re-rendered.</p><ul><li><em>Without any performance optimization:</em></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjolly-sky-d785y&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjolly-sky-d785y&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fd785y%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd55be6ac94720576e902b8c7415ff7f/href">https://medium.com/media/cd55be6ac94720576e902b8c7415ff7f/href</a></iframe><ul><li><em>With shouldComponentUpdate():</em></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fnervous-yonath-r8mdc&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fnervous-yonath-r8mdc&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fr8mdc%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/27e7b7621849fc927aa01f3d39ab0405/href">https://medium.com/media/27e7b7621849fc927aa01f3d39ab0405/href</a></iframe><h3>2. React.PureComponent:</h3><ul><li>React also provides React.PureComponent which does shallow comparision of props and state to skip the re-rendering.</li><li>Using this we don’t have to write shouldComponentUpdate() manually, PureComponent internally manages it.</li></ul><blockquote>Our case when delay() function should be skipped if prop or state does not changes. We can achieve it using PureComponent.</blockquote><pre>import React from &quot;react&quot;;</pre><pre>class Child extends React.PureComponent {<br>  delay() {<br>    console.log(&quot;[Delay] function called&quot;);</pre><pre>for (let i = 0; i &lt; 800000000; i++) {<br>      i++;<br>    }<br>    return &quot;delayed text&quot;;<br>  }</pre><pre>render() {<br>    console.log(&quot;[Child] rendered&quot;);</pre><pre>return (<br>      &lt;div className=&quot;child&quot;&gt;<br>        &lt;hr /&gt;<br>        &lt;div&gt;{this.delay()}&lt;/div&gt;<br>        Selected Color: {this.props.color}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Child;</pre><blockquote>It is much clearer code and does the work if shallow comparision works fine.</blockquote><h4><strong>But it does not work if there is complex data structure or state is mutated in any way [Like exmaple below]:</strong></h4><ul><li>Parent component use select to push selected colors to array.</li><li>Child component receives the color prop as array of colors.</li></ul><p><em>Parent Component:</em></p><pre>import React from &quot;react&quot;;<br>import Child from &quot;./Child&quot;;</pre><pre>class Parent extends React.Component {<br>  constructor() {<br>    super();<br>    this.state = {<br>      color: [&quot;red&quot;]<br>    };<br>  }</pre><pre>render() {<br>    return (<br>      &lt;div className=&quot;container&quot;&gt;<br>        &lt;select<br>          onChange={(e) =&gt; {<br>            console.log(this.state.color);<br>            let updatedColor = this.state.color;<br>            if (Array.isArray(this.state.color)) {<br>              updatedColor.push(e.target.value);<br>            }<br>            return this.setState({ color: updatedColor });<br>          }}<br>        &gt;<br>          &lt;option value=&quot;red&quot;&gt;red&lt;/option&gt;<br>          &lt;option value=&quot;blue&quot;&gt;blue&lt;/option&gt;<br>          &lt;option value=&quot;grey&quot;&gt;grey&lt;/option&gt;<br>        &lt;/select&gt;</pre><pre>&lt;Child color={this.state.color} /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Parent;</pre><p><em>Child Component:</em></p><pre>import React from &quot;react&quot;;</pre><pre>class Child extends React.PureComponent {<br>  render() {<br>    return (<br>      &lt;div className=&quot;child&quot;&gt;<br>        &lt;hr /&gt;<br>        Selected Color:<br>        &lt;ul&gt;<br>          {this.props.color.map((el, index) =&gt; {<br>            return &lt;li key={index}&gt;{el}&lt;/li&gt;;<br>          })}<br>        &lt;/ul&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Child;</pre><blockquote>Here child component doesn’t re-render even if you change the values in colors array.</blockquote><blockquote>Array is a reference type data struture in javascript and because PureComponent only does shallow comparision and both references are same each time.</blockquote><blockquote>To avoid this we can avoid mutation and send new array or objects each time.</blockquote><p><strong>Live codesandbox url of PureComponent example where it state is mutated:</strong></p><ul><li>Please check the console here: as we select any color it adds it to the state array but doesn’t re-render the child component.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsilly-solomon-m2jwk&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fsilly-solomon-m2jwk&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fm2jwk%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a167865ee4233068e3063c0b882632f/href">https://medium.com/media/8a167865ee4233068e3063c0b882632f/href</a></iframe><h3>3. React.memo:</h3><ul><li>It is a higher order component.</li><li>It is similar to React.PureComponent but for function components instead of classes.</li><li>But only shallow compares the props not state as there is no single state object to compare.</li></ul><p>Our case when delay() function should be skipped if prop or state does not changes. We can achieve it using memo().</p><pre>import React from &quot;react&quot;;</pre><pre>function Child (props) {<br>    function delay() {<br>        for (let i = 0; i &lt; 800000000; i++) {<br>            i++;<br>        }<br>        return &quot;delayed text&quot;;<br>    }</pre><pre>return (<br>    &lt;div className=&quot;child&quot;&gt;<br>        &lt;hr /&gt;<br>        &lt;div&gt;{delay()}&lt;/div&gt;<br>        Selected Color: {props.color}<br>    &lt;/div&gt;<br>    );<br>}</pre><pre>export default React.memo(Child);</pre><blockquote>Just wrap your component in React.memo() and it does shallow comparision on props.</blockquote><p><strong>Note by React docs:</strong> All the above methods only exists as a performance optimization. Do not rely on it to prevent a render, as this can lead to bugs`</p><p>References:<br>[<a href="https://reactjs.org/docs">React docs</a>]</p><p>Thanks for reading the article! <br> <br>We can connect on <a href="https://twitter.com/geekrk">twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30ad5b2a03cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>