useMemo overdose
Recently, I've been asked when to use the React's useMemo hook, and this question made me think and reflect on it.
Hey, it’s Edvins. Happy Tuesday! It’s going to be a great week!
Let’s talk about React’s useMemo hook. Recently, I realised that I had fallen into the habit of using the useMemo
hook for pretty much everything, and I couldn't explain why I was doing it. And especially what made me feel worried is that after a chat with another front-end engineer, I've realised I'm not the only one doing it. It means developers tend to overuse the hook and can't adequately explain why they are doing it. This post will teach us when to use the useMemo
hook and when not.
useMemo overuse
tl;dr
Profile first, optimise second. Before optimising a component, use React's built-in tools to accurately profile performance and identify bottlenecks.
Memoise only expensive computations. Apply
useMemo
only to genuinely resource-intensive computations that occur frequently.Keep dependencies accurate. Double-check that all relevant dependencies are provided correctly to
useMemo
to ensure it updates when needed.