Our React project has a code written in Composition Pattern as below.
return (
<Template
title={
useMemo(
() => (
<>
<TitleComponent prop={value} />
<TitleComponent prop={value} />
</>
),
[deps]
)
}
/>
)
I didn't apply useMemo to TitleComponent at first. According to this article, I thought it would be optimized just by delivering components to prop.
However, my colleague argues that it is better to use useMemo because if you apply useMemo, you can skip the render phase. Otherwise, he claim that only the commit phase is skipped.
I'm not going to answer your questions since I think you're confused on what really is the purpose of that hook. Instead I'll give you a better understanding on it.
useMemo
is used when you have a very heavy computation inside a component. What that hook does is, it takes a state/props as dependencies and it wont re-execute the computations unless those dependencies change. Meaning if you have a component that does very heavy computations on render that causes your app to slow down, you need to wrap the computation inside a useMemo
to prevent recomputing your heavy calculations during rerender. In your case, do you have heavy computation on that title component? Absolutely NOT. So you are using that hook wrong.
What you need is React.memo
. This one will convert your component into PureComponent
which will skip unnecessary rerenders if your component only displays static content that doesn't change.