Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

I am trying to check if I set the same value to state as it has previously , does it re-render the component , or if it found that value is same then it will avoid the re-rendering.

like image 902
Vishal Pachpande Avatar asked Oct 03 '18 10:10

Vishal Pachpande


1 Answers

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
like image 116
Estus Flask Avatar answered Sep 28 '22 02:09

Estus Flask