You type into a search box, and every letter appears late, as if the keyboard were stuck. The cause often isn't the box at all, but some heavy calculation elsewhere in the same component that runs again on every keystroke.
Every time state changes, React runs your component function again from the top (a re-render). Everything inside it runs again too: calculations, creating objects, and creating functions. Usually all of that is fast and fine. useMemo and useCallback are two ways to remember something from the previous render, so that thing isn't made again when the values used to make it haven't changed. It's like a cashier who has just calculated the total of a long shopping list. If the customer only asks "what was the total again?", the cashier reads the note instead of adding every item again. The cashier only calculates again when what's in the basket changes. In React, calculating the total is the heavy calculation, the note is the remembered value, and what's in the basket is the dependency: a value that makes the calculation run again when it changes.
Every render runs all the code again
This component has a slow calculation, factorial, and a text field:
function factorial(n) {
const end = performance.now() + 80 // fake load: 80 ms
while (performance.now() < end) {}
let product = 1
for (let i = 2; i <= n; i++) product *= i
return product
}
function App() {
const [n, setN] = useState(5)
const [text, setText] = useState("")
const result = factorial(n)
return (
<div>
<p>{n}! = {result}</p>
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
)
}
factorial(n)calculates 1 × 2 × ... × n. The two lines above the calculation (endandwhile) are only a fake load, so the calculation feels heavy, like filtering thousands of items.const result = factorial(n)sits in the component body, so it runs on every render.- Every keystroke calls
setText, and React rendersAppagain. The calculation runs along with it, even thoughndidn't change.
Take a guess first: you type test into the text field, which has nothing to do with n. Without useMemo, how many times is factorial calculated again? (The Increase n button in the last row of the table adds one to n. Its code is in the Child example below.)
| Event | App render no. |
factorial runs, without useMemo |
factorial runs, with useMemo |
|---|---|---|---|
| first show | 1 | 1 | 1 |
| type t | 2 | 2 | 1 |
| type e | 3 | 3 | 1 |
| type s | 4 | 4 | 1 |
| type t | 5 | 5 | 1 |
click Increase n, n becomes 6 |
6 | 6 | 2 |
Typing test means 4 new renders. Without useMemo, the calculation runs again on each of those renders, so 4 times: 4 × 80 ms = 320 ms of slow typing.
useMemo: remember a calculated result
Wrap the calculation in useMemo:
const result = useMemo(() => factorial(n), [n])
- The first argument is a function that does the calculation. The second is the dependency array: the list of values the calculation uses.
- On the first render, React runs the function and remembers the result.
- On later renders, React compares each value in the dependency array with the previous render. If they are all the same, React returns the old result without calling the function. If one is different, React calculates again.
- Typing in the text field doesn't change
n, so the old result (120) is used again. Only whennbecomes 6 is the result calculated again: 720.
useCallback: remember the function itself
Functions are made new on every render too. const handleAdd = () => setN((c) => c + 1) produces a new function each time. Two functions with the same body still count as different: (() => {}) === (() => {}) is false. Usually that's no problem. The problem only starts when that function is passed as a prop to a component wrapped in memo.
memo(Component) makes a component skip its re-render when all its props are the same as in the previous render. The details are in the next lesson, React.memo. For now, just know this: when a prop is a new function, memo treats the props as changed.
In this example, Child is wrapped in memo and gets handleAdd through the prop onAdd:
const Child = memo(function Child({ onAdd }) {
console.log("Child rendered")
return <button onClick={onAdd}>Increase n</button>
})
function App() {
const [n, setN] = useState(5)
const [text, setText] = useState("")
const result = useMemo(() => factorial(n), [n])
const handleAdd = useCallback(() => setN((c) => c + 1), [])
return (
<div>
<p>{n}! = {result}</p>
<Child onAdd={handleAdd} />
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
)
}
useCallback(fn, [])returns the very same function on every render, as long as its dependencies don't change. An empty dependency array means the function is always the same.setN((c) => c + 1)uses an updater function: React gives the latestnasc. SohandleAdddoesn't need to readn, and its dependency array can stay empty.- When you type in the text field,
Apprenders again, buthandleAddis still the same function.memofinds all the props ofChildunchanged, soChildis skipped.Child renderedisn't printed again. useCallback(fn, deps)is the same asuseMemo(() => fn, deps). So the only difference between the two hooks is what's remembered:useMemoremembers the value its function returns, anduseCallbackremembers the function itself.
Child wrapped in memo? |
handleAdd uses useCallback? |
When you type |
|---|---|---|
| no | no | Child renders again |
| no | yes | Child renders again, the useCallback is wasted |
| yes | no | Child renders again, because its prop is a new function |
| yes | yes | Child is skipped |
When you don't need them
- Cheap calculations.
count * 2is faster to calculate than to remember.useMemohas its own cost: storing the result and comparing dependencies on every render. - A child that isn't wrapped in
memo.useCallbackdoes nothing, because that child re-renders with its parent anyway. - Nothing feels slow yet. Use them only once there's a real problem, for example one you can see in the React DevTools Profiler (a tool that measures how long each render takes). Don't use them everywhere.
- Projects with the React Compiler. The React Compiler is an official build tool from the React team (stable since 2025, the best fit with React 19). It remembers calculated results and functions automatically, the way you do with
useMemoanduseCallback. In projects that use it, you rarely need to writeuseMemoanduseCallbackyourself. In a new Vite project, the compiler is already set up if you pick theJavaScript + React Compilervariant innpm create vite@latest. Many projects don't use it yet, and the exercise editor here has no compiler either. So you still need to understand howuseMemoanduseCallbackwork.
⚠️ Memos that never update, or make no difference at all
- Forgetting the dependency array.
useMemo(() => factorial(n))with no array is calculated on every render, no better than having nouseMemo. - Missing dependencies.
useMemo(() => factorial(n), [])remembers the first result forever: even whennchanges, the result stays 120. Put in every value read inside it. - Reading old state in
useCallback.useCallback(() => setN(n + 1), [])always usesnfrom the first render, sonstops at 6. UsesetN((c) => c + 1), or use[n]as the dependency array. - Side effects in
useMemo. Fetching or timers aren't calculations. They belong inuseEffect.
TL;DR: Every render runs all the code in the component again. useMemo(() => calculate(n), [n]) remembers the value of a heavy calculation, and only calculates it again when a dependency (a value in the array [n]) changes. useCallback(fn, deps) remembers the function itself, the same as useMemo(() => fn, deps). useCallback only helps when that function is passed to a child wrapped in memo (which skips its re-render when its props are the same). Write the dependencies in full, and use an updater function such as setN((c) => c + 1) so useCallback doesn't read old state. Cheap calculations and children without memo need neither. In projects with the React Compiler (a build tool from the React team), the compiler remembers calculated results and functions automatically.
⚡ Every render runs all the code again
Guess first: the component App has a heavy calculation, factorial(n) (80 ms), in its body, and a text field. You type test into that text field, which has nothing to do with n. Without useMemo, how many times is factorial calculated again?
Four times, once per letter. Every keystroke causes a render, and every render runs all the code in the component again: 4 × 80 ms = 320 ms of slow typing.
Meaning: Every keystroke changes state, then React renders again. A heavy calculation in the component body runs on every render, even when n didn't change.
⚡ useMemo: remember the result
Write:
const result = useMemo(() => factorial(n), [n])
Meaning: useMemo takes a function that does the calculation and a dependency array [n] (the values the calculation uses). React remembers the result, and only calculates it again when n changes. Typing in the text field doesn't change n, so the old result is used again.
⚡ useCallback: remember the function
Write:
const handleAdd = useCallback(() => setN((c) => c + 1), [])
Meaning: Without useCallback, handleAdd is a new function on every render. The dependency array is empty ([]), because setN((c) => c + 1) uses an updater function and doesn't need to read n. useMemo remembers the value its function returns, while useCallback remembers the function itself. useCallback only helps when handleAdd is passed as a prop to a child wrapped in memo, which is a component that skips its re-render when its props are the same.