Is it safe to useMemo for JSX?
Memoizing JSX expressions is part of the official useMemo
API:
const Parent = ({ a }) => useMemo(() => <Child1 a={a} />, [a]);
// This is perfectly fine; Child re-renders only, if `a` changes
useMemo
memoizes individual children and computed values, given any dependencies. You can think of memo
as a shortcut of useMemo
for the whole component, that compares all props.
But memo
has one flaw - it doesn't work with children:
const Modal = React.memo(ModalView);
// React.memo won't prevent any re-renders here
<Modal>
<CreateChannel />
</Modal>
children
are part of the props. And React.createElement
always creates a new immutable object reference (REPL). So each time memo
compares props, it will determine that children
reference has changed, if not a primitive.
To prevent this, you can either use useMemo
in parent App
to memoize children
(which you already did). Or define a custom comparison function for memo
, so Modal
component now becomes responsible for performance optimization itself. react-fast-compare
is a handy library to avoid boiler plate for areEqual
.