PT-BR EN
Blog

How to Use useMemo

2 min read
How to Use useMemo

What is useMemo

Imagine you are building a complex screen in React and run into the following situation:

I want to store an already computed value instead of redoing the calculation every time the component renders.

The concept of memoization

useMemo is the hook that implements memoization inside React. But what is memoization? Memoizing is basically calculating once and storing the result. It is a kind of cache that prevents the same calculation from being redone unnecessarily.

Imagine your job is to count the potholes in the pavement of a street and report the number to drivers. When the first driver asks, you will spend a good amount of time counting. When the next one passes, you don’t need to count again, because, being smart, you wrote down how many potholes there were. But if the city hall fills some of them in, your note becomes invalid and you need to count again.

Parameters

The signature of useMemo is:

const value = useMemo(() => {
  return computeSomething();
}, [dependencies]);

The first parameter is a function with no arguments, whose return value will be stored. The second is an array of dependencies, which serves to invalidate the cache when one of its values changes.

Return value

useMemo returns the same value returned by the function passed as the first parameter. Usually, that value is assigned to a variable.

Important notes

  • The function passed to useMemo must be pure, meaning it has no side effects, because it runs during rendering.
  • React may discard the cached value and recompute it, so useMemo should be treated as a performance optimization, not as a storage guarantee.
  • It is only worth using it for genuinely expensive calculations or to keep the same reference for objects and arrays between renders.

Practical example

The example puts two side-by-side components that compute the same slow Fibonacci (recursive, intentionally heavy), but one uses useMemo and the other computes directly in the component body. The Demo (parent) has a counter unrelated to the calculation, used only to force re-renders of the children. When you click “Increment”, the component without useMemo recalculates the Fibonacci on every render (the screen freezes a bit and its calculation counter goes up), while the component with useMemo reuses the stored value, because num, its only dependency, didn’t change, and its counter stays still. useRef is used to count the executions without causing new renders. When the input number actually changes, both recalculate, since that is when the cache doesn’t apply.