Performance optimization with react PureComponent and React memo
Tags: react
Published: 2020-03-18 10:26:09

<!-- wp:paragraph -->
<p>Before digging into the PureCompoment thoroughly let's understand the difference between React component and PureComponent</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>NOTE</strong>: Considering you have basic knowledge of react.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In React Component, If you want to optimize performance then we have to implement shouldComponentUpdate lifecycle method where we can add condition check to see is props or state has been different from previous ones or not If it changed then only we will return true in shouldComponentUpdate method which will force to call render method otherwise render will get called every time props or state changed.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>What PureComponent makes different from Component?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you are extending the PureComponent class then you don't need to take care of shouldComponentUpdate lifecycle method. PureComponent itself takes care by shallow checking states and props. If it finds states and props are different from the previous state and props then only it calls render method else not.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>What does shallow check mean?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> Shallow compare does check for equality. When comparing primitive values (numbers, strings) it compares their values. When comparing nonprimitive like objects or arrays, it does not compare their's attributes - only their references are compared </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For eg., If you have an array and you are pushing element to an existing array then PureComponent does not trigger render method because as per PureComponent there is no change happened because reference is still the same</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's go by example</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import React, { PureComponent } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends PureComponent {
  constructor() {
    super();
    this.state = {
      personArr: [
        {
          name: "abc",
          age: "22 years",
          gender: "male"
        },
        {
          name: "pqr",
          age: "23 years",
          gender: "female"
        },
        {
          name: "mno",
          age: "24 years",
          gender: "male"
        }
      ]
    };
  }
  addPerson() {
    var persons = this.state.personArr;
    persons.push({
      name: "xyz",
      age: "32 years",
      gender: "male"
    });
    this.setState({
      perosnArr: persons
    });
  }

render() {
    const persons = this.state.personArr.map((person, index) => {
      return (
        &lt;section>
          &lt;div>
            &lt;label>Name:&lt;/label> {person.name}
          &lt;/div>
          &lt;div>
            &lt;label>Age:&lt;/label>
            {person.age}
          &lt;/div>
          &lt;div>
            &lt;label>Gender:&lt;/label>
            {person.gender}
          &lt;/div>
        &lt;/section>
      );
    });
    return (
      &lt;div className="App">
        &lt;button onClick={() => this.addPerson()}>Add person&lt;/button>
        {persons}
      &lt;/div>
    );
  }
}

render(&lt;App />, document.getElementById('root'));
</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As you can see in the above code we are rendering a person's array and also we have added person button which pushing person object to an existing array.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>so, Here PureComponent not let render method run because here an array is a non-primitive type so reference has been checked.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here I think you might be thinking why PureComponent only checks the reference, not internal attributes because if react implements this logic then it's going to be a very expensive operation performance-wise.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> Still, you want to run the render method after pushing element to an array then you should not mutate existing array, even react suggest should not mutate existing element.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For eg.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>addPerson(){
  const perosnArr = this.state.personArr;
  perosnArr.push({
    name: "xyz",
    age: "32 years",
    gender: "male"
  })
  this.setState({
    perosnArr: {...personArr}
  })

}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As you can see above I am not mutating existing array, I have created a new array using spread operator now the reference is different for old and new array so now render method will trigger.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Please check the example <a href="https://stackblitz.com/edit/react-dij6dw">here</a></p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Improve performance in functional components using React.memo()</h2>
<!-- /wp:heading -->
[For Full post click here](https://techboxweb.com/performance-optimization-with-react-purecomponent-and-react-memo/)