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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With