Does react re-render the component if it receives the same value in state

Class component

A component is unconditionally re-rendered after setState call. It doesn't matter if the state is the same value, i.e. a value that passes === comparison:

this.setState(state => state); // re-render

Or the same state that passes shallow object comparison:

this.setState(state => ({...state})); // re-render

In order to avoid unnecessary re-renders, component updates should be prevented, either with PureComponent or shouldComponentUpdate:

React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If your React component’s render() function renders the same result given the same props and state, you can use React.PureComponent for a performance boost in some cases.

Notice that due to the use of virtual DOM in React, re-renders don't necessarily result in DOM re-rendering and may have acceptable performance.

Function component

useState hook in functional components provides an alternative to stateful class components. One of major differences is that a component isn't re-rendered if it's the same value, i.e. a value that passes === comparison:

const [state, setState] = useState({});
...
setState(state => state); // no re-render

Otherwise a component is re-rendered:

setState(state => ({...state})); // re-render

In the React Documentation - shouldComponentUpdate In Action, they've talked about it in details, as a part of Optimizing Performance topic, and also give an example. This is the example:

enter image description here

Tags:

Reactjs