I have a parent component which looks like this:
const Parent = () => {
return (
<Child_1 />
<Child_2 />
);
}
if any changes occur in one of the child components, will the Parent component re-renders ?
I have a parent component which looks like this:
const Parent = () => {
return (
<Child_1 />
<Child_2 />
);
}
if any changes occur in one of the child components, will the Parent component re-renders ?
No, it will not re-render. If you pass any props to the component from the parent component and you update that prop in children or that prop update in the parent component so both will re-render. But if the data or state has no dependency on the parent component so it will not cause a re-render in the parent component.
State changes in Child component doesn't effect on the parent component, but when a state of parent component changes all the child components render.
No, in your case absolutely not. Let's see when the parent re-renders and when not.
const Parent = () => {
return (
<Child_1 />
<Child_2 />
);
}
This is your case, where the parent does not transfer any state as prop. In this case the child re-renders independently, not causing the parent to re-render.
const Child = ({parentState, setParentState}) => {
return <div onClick={() => setParentState(parentState+1)} >{parentState}</div>
}
const Parent = () => {
const [parentState, setParentState] = useState(0);
return <Child parentState={parentState} setParentState={setParentState}>;
};
In this case, whenever the user clicks on the div of Child, the state parentState
changes, leading to re-render in both Child
and Parent
.