Why use purecomponent when React DOM renders only on difference?

Purecomponent is similar to React.Component, the only difference is that React.PureComponent implements a method called shouldComponentUpdate with shallow prop and state comparison.

React documentation recommends using PureComponent as performance optimization because PureComponent prevents unnecessary renders.

But according to the main concept of React, it updates only what's necessary. Here is the gif from the documentation of React.

React DOM diff rendering
React DOM diff rendering

As you can see above, only the time inside the h2 tags are being updated, and not the entire root id div.

Why use PureComponent when React DOM handles the difference

So the React DOM is intelligent enough to detect what has changed and only re-render that part. When the React DOM handles that for us, why do we have to use PureComponent or shouldComponentUpdate.

The reason is that even if you do not use PureComponent, the child component is going to call the render function when the parent prop changes. React DOM will only update the difference in the previous DOM and current DOM, but it will not prevent the calling of the render function. You can see in the example below.

In the below example, we have two components. The parent component is called App and child component is called Test.

class App extends React.Component {
  state = {
    name: "abc"
  };
  componentDidMount() {
    setInterval(() => {
      this.setState({
        name: "abc"
      });
    }, 1000);
  }
  render() {
    return <Test />;
  }
}
let index = 0;
class Test extends React.Component {
  render() {
    index++;
    console.log(index);
    return <div>Test</div>;
  }
}

Here the Test component extends the React.Component . So every time there is a change in the state of the parent component App, the Test component re-renders irrespective of whether the change is related to Test component or not.

This image has an empty alt attribute; its file name is Screenshot-2019-10-21-at-9.56.11-PM.png
The console of Test component extending React.Component

As you can see above, the index is updated every second - meaning the Test component is being re-rendered.

When you extend the Test compoent with React.PureComponent, then it will not update the console - meaning the Test component is not re-rendering unnecessarily.

Here is the comparison of the console between Test as Component vs PureComponent.

React.Component
React.Component
React.PureComponent
React.PureComponent

Conclusion

PureComponent or shouldComponentUpdate exists for performance improvement. ReactDOM will help in rendering the difference, and not update the entire UI in the DOM, but it cannot prevent the un-necessary calling of the render function in the component. So we should use PureComponent or shouldComponentUpdate wherever applicable.