When will a React component using hooks re-render?
Let's assume the component:
useState
props
from its parentWill a re-render happen directly after the following events, and only at those points in time?
props
state
is updatedRelated Question
Let's assume the component has several useState
expressions and a user interaction causes multiple states to update.
Will the component re-render multiple times, once per state
value that changed, or will it batch these related changes into one single re-render?
Found this nice article on this topic. I'll add the summary in case someone needs a quick read.
State modification
Component re-renders when its state is manipulated, simple as that. So, when you modify the state of your component it tends to re-renders with the new state value.
Passing Props
If the parent component has triggered a rerender all the child component will rerender too, generally you would only want the specific child components to rerender only if the component is consuming some props or the passed props are modified but that isn’t the case, it does not matter if the props are consumed, modified or not, the child components will re-render if the parent component has triggered a render.
Using the Context API
When modifying the state which is also the value passed to the context, the whole child components tree would get rerendered. Again doesn’t matter if the child component is consuming the context data or not, it will still rerender. The rerenders depend on the value passed to the provider but still, all the whole components tree would get rerendered.
Passing down references
In case of an object, array and, function comparison is based on references i.e. the exact memory location so, their comparison even though they seem equal yields false, in React Object.is method is used to compare the different values.
Example:
{}==={} //false
[]===[] //false
{a: 5}==={a: 5} //false
[1,2,3]===[1,2,3] //false
(when comparing the previous state to the new state, it returns false because they do not have the same reference. Only the value is the same)
A component will re-render in the following cases considering it doesn't implement shouldComponentUpdate for class component, or is using React.memo for function
Let's assume the component has several useState expressions and a user interaction causes multiple states to update.
Will the component re-render multiple times, once per state value that changed, or will it batch these related changes into one single re-render?
useState
doesn't merge the updated values with previous ones but performs batching like setState
and hence if multiple state updates are done together, one render take place.
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