useMemo
and useCallback
are both React hooks that help in optimizing the performance of React applications by memoizing (caching) SOMETHING so that you don't keep doing the same calculation every time you re-render a page.
Although they seem similar because both cache the results of computations to avoid unnecessary recalculations, they serve different purposes and are used in different scenarios.
I thought I'd write it down, if only to have something to look at when I need to remind myself for the 100th time.
Re-rendering
Just to review, React will perform a re-render for lots of reasons-- state changes, props changes, manual re-renders, context changes, etc.
Anything that isn't protected by a hook wrapper are going to get re-run each time. If that thing is expensive, e.g., some fancy calculation, it can impact your page's performance significantly.
The hooks useMemo
and useCallback
were designed to avoid this unnecessary repetition. At first glance, they sound very similar. So, how do they differ?
useMemo
useMemo
is a hook that memoizes the result of a function. It will only recompute the memoized value when one of its dependencies has changed. This optimization helps to avoid expensive calculations on every render.
Syntax:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
- Purpose: To memoize the result of an expensive calculation.
- Use Case: When you have a computation that is expensive to run on every render and the result of that computation is used directly in the JSX or in other calculations.
useCallback
useCallback
is a hook that memoizes a callback function. Similar to useMemo
, it will only change the memoized function if one of the dependencies has changed. This is particularly useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
Syntax:
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
- Purpose: To memoize a callback function.
- Use Case: When you pass callbacks to child components and you want to prevent those components from re-rendering unless the functions have changed. This is important for performance optimization in components that rely on reference equality to avoid unnecessary updates (e.g., shouldComponentUpdate, React.memo).
Key Differences
- Use Cases:
useMemo
is used to memoize values/results of computations.useCallback
is used to memoize functions to ensure their reference stability across renders. - Return Values:
useMemo
returns the memoized result of the function.useCallback
returns the memoized function itself.
To summarize, while both useMemo
and useCallback
aim to optimize performance by memoizing values and functions, respectively, their main difference lies in what they are memoizing: useMemo
memoizes computation results, while useCallback
memoizes function instances.