I have played around with react for a while and read docs, and I find something that seems weird for me, why react rerender children elements of a component on every state change of the parent even if the child props are the same ?? why I should wrap my component inside Memo() to prevent this rerender? Isn't better to make Memo the default for every react Component or should I use it for all my components.
-
That's how react works. Even if state is being updated that is not passed to a child, it will rerender. You will need to use memo, if you don't want your child to rerender. – FireFighter Apr 22 '21 at 13:48
-
Related: https://stackoverflow.com/questions/61301937/why-is-react-component-rerendering-when-props-has-not-changed – Ciro Santilli OurBigBook.com Dec 11 '21 at 10:34
3 Answers
On every state change react triggers a render function, which in return calls its child components to rerender, please find below example to solve your problem, or visit https://www.robinwieruch.de/react-prevent-rerender-component
function Parent() {
const [item, setItem] = useState({ name: "item", value: 0 });
const handleChangeItem = useCallback(() => {
setItem(prevItem => ({ ...prevItem, value: prevItem.value + 1 }));
}, []);
return (
<>
Name: {item.name} Value: {item.value}
<Child changeItem={handleChangeItem} />
</>
);
}
const Child = React.memo(function Child({ item, changeItem }) {
function handleClick() {
changeItem();
}
console.log("child render");
return (
<div>
<button onClick={handleClick}>change state in parent</button>
</div>
);
});

- 914
- 7
- 16
memo is the implementation of PureComponent but for functional components. PureComponent would do the shallow comparison of props in class components, while with functional components you use memo
, useMemo
(to memoize values), and useCallback
(to memoize functions).

- 177
- 4
-
Is it always good to wrap your component inside the memo function? and if not when to use it ? – T.arar Apr 22 '21 at 14:04
-
i would wrap my component in `memo` when I pass it callbacks as props (callbacks must be wrapped in useCallback then). Each time the parent component re-renders it creates a NEW callback function and sends it down to its child. The child 'sees' a new function (since it's a different object) and re-renders because a new prop came. `useCallback` memoizes the callback function and `memo` turns your component into a Pure FC that will perform shallow comparison of props. Here's a good [resource](https://dmitripavlutin.com/use-react-memo-wisely/) – Andrii Lukianenko Apr 22 '21 at 14:25
Try to use PureComponents as react rerenders every time on a state change and if your parent component rerenders, then all your child components will rerender in the same order as well. To avoid rerendering child components you can use React.Memo, useMemo, or useCallback. Though it is not good every time to memoize components.

- 594
- 2
- 9