Skip to content
tezvyn:

React's useMemo Hook: Cache Expensive Calculations

Source: react.devMediumHow cards are made

React's useMemo Hook: Cache Expensive Calculations

useMemo is React's cache for expensive calculations, preventing re-computation on every render. Use it for heavy tasks like filtering large lists. The main footgun is an incomplete dependency array, which leads to stale, cached data.

Why it exists

React components re-render whenever their state or props change. By default, this means all code inside the component body runs again, including potentially slow calculations. useMemo was created to provide a performance escape hatch, allowing developers to skip these expensive re-calculations when they aren't necessary.

The mental model

Think of useMemo as a cache for a single value within your component. You give it a function that produces a value and a list of "ingredients" (dependencies) that go into that function. React will only re-run the function to get a new value if one of the ingredients has changed since the last render. Otherwise, it serves the cached value, saving computation time.

How it works

You call useMemo at the top level of your component, passing two arguments: a "create" function and a dependency array. On the first render, React executes the create function, stores its result, and returns it. On subsequent renders, React compares each item in the dependency array with its value from the previous render using Object.is comparison. If all dependencies are the same, React returns the stored result without calling the create function. If any dependency has changed, React re-runs the create function, stores the new result, and returns it.

When to use it

Use useMemo for computationally expensive operations that you don't want to run on every render. Three common scenarios are: first, filtering, sorting, or transforming a large array; second, wrapping a value (like an object or array) that you pass as a prop to a component wrapped in React.memo to prevent it from re-rendering unnecessarily; third, as a dependency for another hook like useEffect to control when the effect re-runs.

When not to use it

Avoid useMemo for cheap calculations. The overhead of checking dependencies can be more expensive than simply re-running the calculation itself. Also, don't use it if the calculation must run on every render. Remember that useMemo is a performance optimization, not a semantic guarantee; React may discard the cache for reasons like memory pressure. Premature optimization with useMemo can make code harder to read without providing any real benefit.

One canonical example

Imagine a TodoList component that receives a large todos array and a tab prop ('all', 'active', 'completed'). Filtering the list can be slow.

const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);

Here, filterTodos is the expensive calculation. It will only re-run if the todos array or the tab string changes. If the component re-renders for another reason, useMemo returns the previously calculated visibleTodos array, saving a costly re-filter.

Interview question

What is the primary benefit of using React's useMemo hook in a component?

  • a.To cache the result of an expensive calculation, re-running it only when its specific dependencies have changed.Correct
  • b.To ensure that a value is always re-calculated on every render, guaranteeing its freshness.
  • c.To manage asynchronous operations and ensure data is fetched efficiently.
  • d.To prevent the component itself from re-rendering unnecessarily when its props or state remain the same.
Why?

useMemo's core function is to cache the result of a function, preventing it from re-executing on every render unless its specified dependencies change. While it can indirectly support preventing component re-renders (e.g., when passing memoized objects to React.memo components), its direct benefit is optimizing expensive calculations within a component.

Just read this? Test yourself on what you have been reading.

Read the original → react.dev

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on react — each one lists the topics its interview covers.

See open roles