A child component is re-rendered in react in three cases:
1.) If the parent component is re-rendered, then the child will be re-rendered.
2.) If the state of the parent component is updated using useState or useReducer. -> then parent component will re-render, then the child will be re-rendered.
3.) If the props of child component is updated, it will be re-rendered. (It is the main point, all other point are related to this point only.)
we can make use of React.memo or passing child as a prop to prevent form unnecessary re-rendering.
(passing child as a prop will also work beacuse apart from React.memo because a component can not change its own prop)
Also, when we pass objects or function as a prop which remains same, then to avoid unnecessary rendering of child component, we can make use of useCallback and useMemo hook.
This is because when we pass objects or function as prop from parent component, when the parent component re-renders due to some state change, a new refernce to object and function is created, which will be treated as a new prop that to be passed to the child component. So to prevent that, we make use of useMemo(for non primitive values like object and arrat) and useCallback(for functions)
Top comments (0)