What is useCallback?
- React course
- Intermediate
- Lesson 25/80
- 4 min
Learn to cache a function with useCallback.
What is useCallback?
useCallback caches a function; it returns the same reference as long as dependencies don't change. Use it as const handler = useCallback(() => { ... }, [deps]);.
useMemo is for values, useCallback is for functions. Both share the same caching logic. useCallback is essentially shorthand for useMemo(() => fn, deps).
The most common use: keeping functions passed as props to child components stable. If the child is wrapped with React.memo, it won't re-render while the prop keeps the same reference. This is a serious speed boost for big lists.
Why same reference matters
In JavaScript, every function definition creates a new object. In function App() { const h = () => 0; return <Child onH={h} />; }, a new h function is born on every render.
If Child is wrapped with React.memo, it compares props by value. But functions are compared by reference, so each render shows a different one and Child re-renders.
useCallback solves this: with the same dependencies, the function reference is kept. Combined with React.memo, needless renders are prevented.
Practice useCallback skeleton
Complete the skeleton. Write a Counter component. Define count with useState(0). Define increment with useCallback(() => setCount(c => c + 1), []). Show <button onClick={ '{ increment }' }>Increment</button> and <p>{ '{ count }' }</p>. Export it.
Starter code
import { useState, useCallback } from "react";
// Write the Counter component hereSample solution
import { useState, useCallback } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount((c) => c + 1), []);
return (
<div>
<p>{count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does useCallback cache?
- Value
- Function Correct answer
- State
- DOM
Explanation: useCallback caches a function.
2 useCallback vs useMemo
useCallback is for functions, useMemo is for ____.
useCallback is for functions, useMemo is for values.
Explanation: useMemo caches values.
3 Match the useCallback steps
| Term | Meaning |
|---|---|
function |
cache |
dependency |
triggers |
same ref |
stable |
React.memo |
child |