This is something that has been bothering me for some time and I think it's time to clear up the issue.
In the Codesandbox.io you can see that Countdown component rerenders whole parent component. This happens only when I display SubComponent. You can try and replace with and counter only rerender itself.
Help my out here because I have no idea why react behaves like this.
Thanks!
CodePudding user response:
In the counter component you are calling setState (setCounter) which is updating the state of the parent component. When the state of parent component is updated as you are using useState Hook. It will re render the whole component and as the whole component is getting re rendered you have alse declared
const SubComponent = () => {
return <SubSubComponent />;
};
this SubComponent will again get declared and initialized ( Every time the component gets re rendered ).
There is actually no need to declare this SubComponent inside the App component you can simply use it.
If you don't want the component to get new instance of it every time you can use techniques like memoization so that the SubComponent only gets re rendered when something in props changes. Also useCallback to only create new function when something in its dependency changes.
CodePudding user response:
In the Codesandbox.io you can see that Countdown component rerenders whole parent component. This happens only when I display SubComponent.
Even if you have subcomponent or not, it is going to rerender parent because state is present inside the parent App component.
Your subcomponent is also getting re-rendered because every time you are creating a new instance of it.