# useMemo & useCallback

> How to cache expensive calculations and preserve object references between renders to optimize your React applications.

Subject: React | Lesson 31 of 48 | 5 min read
Interactive lesson: https://codewithanimation.in/react/usememo-and-usecallback
Previous: [React.memo](https://codewithanimation.in/react/react-memo.md) | Next: [The Over-Optimization Trap](https://codewithanimation.in/react/over-optimization-trap.md)

## Caching Values and Functions

In React, every time a component re-renders, its entire function body executes from top to bottom. This means all local variables are re-calculated, and all local functions are re-defined in memory.

`useMemo` is a hook that caches the *result* of a calculation. It only re-calculates when its dependencies change.

`useCallback` is almost exactly the same, but it caches a *function definition* instead of a value.

## The Two Main Use Cases

**1. Skipping Expensive Math:** If you are filtering an array of 10,000 items, you don't want to re-run that loop every time the user types in an unrelated text input. `useMemo` caches the filtered array.

**2. Preserving Referential Equality:** As we learned in `React.memo`, if you pass an object `{}` or a function `() => {}` as a prop to a memoized child, it breaks the memoization because `{}` !== `{}`. You must wrap the object in `useMemo` or the function in `useCallback` to ensure the memory address stays identical across renders.

## Syntax and Dependency Arrays

Both hooks take two arguments: the thing to cache, and a dependency array (just like `useEffect`).

`const sortedData = useMemo(() => heavySort(data), [data]);`

`const handleClick = useCallback(() => submit(id), [id]);`

React will return the exact same cached value/function on subsequent renders, *unless* the variables in the dependency array have changed.

## Common mistake: The Performance Irony

A very common anti-pattern is using `useMemo` for simple operations, like `const num = useMemo(() => 5 * 2, [])`.

Calling the `useMemo` hook, allocating memory for its cache, and running the dependency array comparison actually costs *more* CPU cycles than just calculating `5 * 2`.

Only use these hooks for genuinely slow operations (e.g., complex array transformations) or to maintain referential equality for child components.

## Tip: useCallback is just useMemo for functions

Under the hood, `useCallback(fn, deps)` is literally just syntax sugar for `useMemo(() => fn, deps)`. They do the exact same thing: cache a reference in memory.

## Try it: The Price of Re-calculation

Interact with the Dashboard below. It contains a 'Heavy Calculation' (simulated by artificially freezing the thread for 500ms). Notice what happens when you type in the unrelated input field with and without useMemo.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/react/usememo-and-usecallback

## Check yourself

### Question 1

What is the primary difference between `useMemo` and `useCallback`?

- A. `useMemo` runs after the render phase, while `useCallback` runs before it.
- B. `useMemo` caches the result of calling a function, while `useCallback` caches the function itself.
- C. `useMemo` is for primitive values (strings, numbers), while `useCallback` is for complex objects.

Correct answer: B

`useMemo(() => fn(), [])` calls the function and caches what it returns. `useCallback(fn, [])` caches the function itself.

- Why not A: Both run during the render phase.
- Why not C: `useMemo` is often used for complex objects.

### Question 2

Why is `useCallback` often required when passing functions to a child component wrapped in `React.memo`?

- A. Because `React.memo` cannot accept functions as props without it.
- B. Because without it, a new function is created on every render, causing `React.memo`'s shallow comparison (`oldProp === newProp`) to fail.
- C. Because it automatically binds the `this` keyword to the function.

Correct answer: B

Functions in JavaScript are objects. A newly created function has a different memory address than the previous one, forcing the child to re-render.

- Why not A: It accepts them just fine, it just won't optimize the render.
- Why not C: Arrow functions handle `this`, not `useCallback`.

### Question 3

Which of the following is a BAD use case for `useMemo`?

- A. Filtering a list of 5000 users based on a search query.
- B. Caching an object being passed to a heavily memoized data table.
- C. Caching a simple boolean flag: `const isReady = useMemo(() => status === 'active', [status])`.

Correct answer: C

The overhead of calling `useMemo` and checking the dependency array is significantly slower than just doing a simple `===` string comparison on every render.

- Why not A: This is a great use case.
- Why not B: This is necessary to preserve referential equality.

## Remember this

- `useMemo` caches the return value of a calculation.
- `useCallback` caches a function definition.
- Use them to skip expensive calculations (heavy math, large array methods).
- Use them to preserve referential equality when passing props to `React.memo`.
- Do NOT use them for simple, fast calculations. The caching mechanism itself has a performance cost.
