useMemo is a React Hook introduced in React 16.8 that caches the result of a calculation between re-renders to optimize performance by avoiding unnecessary expensive computations. It returns a memoized value that remains unchanged unless one of the specified dependencies in the array changes, compared using the Object.is algorithm.
Core Functionality and Syntax
The hook takes a factory function and a dependency array as arguments: const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);.
Factory Function: A pure function that performs the calculation and returns the value to be cached.
Dependencies: A list of all reactive values (props, state, or variables) used inside the calculation.
Behavior: On the initial render, React executes the function. On subsequent renders, if dependencies remain the same, the cached value is returned; otherwise, the function re-runs.
Key Use Cases and Best Practices
Skipping Expensive Recalculations: Ideal for filtering large arrays or performing heavy computations where the result depends on props or state that might not change every render.
Memoizing Dependencies: Useful for preventing
useEffector other hooks from firing too often by ensuring a stable reference for dependencies.Performance Optimization: Should only be relied upon when calculations are noticeably slow (e.g., taking 1ms or more), as the overhead of memoization can slow down trivial computations.
React Compiler: Modern React versions include a compiler that automatically memoizes values, potentially reducing the need for manual
useMemocalls.
Limitations and Caveats
Top-Level Only:
useMemomust be called at the top level of a component or custom hook; it cannot be used inside loops or conditions.Strict Mode: In development, React may call the calculation function twice to verify purity, but this does not affect production logic.
Reference Equality: For arrays and objects in the dependency array, React checks for reference equality (
===), meaning a new array instance will trigger a re-calculation even if the contents are identical.Not for Side Effects:
useMemois for caching values, not for handling side effects;useEffectis the appropriate hook for that purpose.
Is useMemo still used?
When to use or not use useMemo and useCallback?
How often to use useCallback/useMemo?
What is the purpose of useMemo-ing a whole component? A lack of trust of react change detection? Explicitly stating when the component should re-render?
What is React useMemo?
How does useMemo work in React?
What is difference between useEffect and useMemo?
Videos
I'm starting to learn react and was learning about useMemo for caching. However I ended up finding something that said react is getting a compiler, which would essentially do what useMemo does but better. Is this true? Should I still be learning and implementing useMemo?