Class Components
In React class components, we are told that setState always causes a re-render, regardless of whether or not the state actually changed to a new value. In effect, a component will re-render, when state updates to the same value it was before.
Docs (setState API Reference):
setState() will always lead to a re-render unless shouldComponentUpdate() returns false.
Hooks (Function Components)
With hooks however, the docs specify that updating state to a value identical to the previous state, will not cause a re-render (of child components):
Docs (useState API Reference):
Bailing out of a state update
If you update a State Hook to the same value as the current state, React will bail out without rendering the children or firing effects. (React uses the Object.is comparison algorithm.)
Closely Related Questions
- Is it correct that
this.setStatein class components always cause a re-render, even when the newstatevalue is identical to the previous? - Is it correct that in function components with hooks,
setStatefromuseStateonly causes a re-render if thestatevalue is different from the previous value? - Is setting
statewiththis.setStateinside therendermethod of a class component, the same as settingstateinside the function body of a function component with hooks? - Is the following correct?
- In a class component, if we set
statein therendermethod an infinite loop will occur. This is because the class component does not care that the newstateis the same as the previousstate. It just keeps re-rendering on everythis.setState. - In a function component with hooks however, setting
stateinside the function body (which runs at re-render similarly to therendermethod in class components) would not be an issue, because the function component just bails out of re-renders when it sees that thestateis identical to the previousstate.
- In a class component, if we set