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.setState
in class components always cause a re-render, even when the newstate
value is identical to the previous? - Is it correct that in function components with hooks,
setState
fromuseState
only causes a re-render if thestate
value is different from the previous value? - Is setting
state
withthis.setState
inside therender
method of a class component, the same as settingstate
inside the function body of a function component with hooks? - Is the following correct?
- In a class component, if we set
state
in therender
method an infinite loop will occur. This is because the class component does not care that the newstate
is the same as the previousstate
. It just keeps re-rendering on everythis.setState
. - In a function component with hooks however, setting
state
inside the function body (which runs at re-render similarly to therender
method in class components) would not be an issue, because the function component just bails out of re-renders when it sees that thestate
is identical to the previousstate
.
- In a class component, if we set
we are told that setState always causes a re-render
i'm not sure about this. If you return nullthis.setState(() => null)
, it does not re-render anything. – samb102