Lets say I have a parent component called and I create a useState in it called [value, setValue]. I pass the value and setValue to a child component through props. Please note that the function setState is not used in the parent component and the state ‘value’ is not used in the JSX of the parent. Value is used in the JSX of the child component and and setValue is also used in the child component. Here the child component will definitely re-render when the setValue is used, does the parent component re-render or no?
I did try creating a sample project testing things out myself, I found that both the parent and child component re-rendered twice. I do not understand why this is happening, perhaps I don’t understand how does re-rendering actually work in React.
Please help me solve this confusion.
3
Answers
what happens actually is when the state changes it will re render the component where it is created and all the child component. If you would have created the state inside child component then only the child component would have been re-rendered.
The only thing that causes a Component to re-render in React is a state change. With this state change, React triggers a re-render to keep the Component state in sync with the GUI.
While you say the state is not used in the Parent, it is. Here is a simple example with your terminology for intuition:
When
state
is mutated, theParent
Component is re-rendered such that theChild
Component is also re-rendered. The state changes in theParent
so it is essential to make sure to re-render theParent
so that if there is any part ofParent
thatstate
is used, that part stays in sync with the GUI.What re-renders is
Parent
.Child
re-renders as a consequence of being a descendant ofParent
.When your component is run in strict mode, they will be rendered twice. Source: Docs.
As for why parent component was also re-rendered, I will explain it from inside React.
The function setValue actually had 3 parameters. What you passed to this function was only the last parameter. The first two parameters were passed when you parent component called the useState hook the first time. And they were internal data structures corresponding to the parent component.
Despite where this function was called, you can pass it to child, or deep in the component tree, React would always re-render the component tree starting from where this function was created.