useMemo vs useCallback
- React course
- Intermediate
- Lesson 27/80
- 4 min
Learn the difference between the two hooks.
useMemo vs useCallback
The two hooks are similar but for different purposes: useMemo produces a value, useCallback keeps a function reference stable. In practice, useCallback(fn, deps) === useMemo(() => fn, deps).
For a function returning an object: const data = useMemo(() => ({ '{ a, b }' }), [a, b]) is right; useCallback would be wrong. For an event handler: const handler = useCallback(() => alert(a), [a]) is right.
A confusing case: useMemo(() => () => alert(a), [a]) also stabilizes a function. But useCallback is made for this case; it reads better.
Relationship between them
useCallback is actually a special case of useMemo. useCallback(fn, deps) and useMemo(() => fn, deps) give the same result. useCallback is just shorter and more readable.
Which to pick depends on code readability. For stabilizing a function, useCallback; for stabilizing an object or computation, useMemo. Both work with a dependency array.
The same cautions apply: they may add overhead for small computations and small functions. Avoid adding them everywhere without profiling. React is usually fast enough.
Practice Handler with useCallback
Complete the skeleton. Write a SearchBar component. Define query with useState(""). Define handleChange with useCallback((e) => setQuery(e.target.value), []). Show <input value={ '{ query }' } onChange={ '{ handleChange }' } placeholder="Search" />. Export it.
Starter code
import { useState, useCallback } from "react";
// Write the SearchBar component hereSample solution
import { useState, useCallback } from "react";
function SearchBar() {
const [query, setQuery] = useState("");
const handleChange = useCallback((e) => setQuery(e.target.value), []);
return <input value={query} onChange={handleChange} placeholder="Search" />;
}
export default SearchBar;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which to stabilize an event handler?
- useState
- useMemo
- useRef
- useCallback Correct answer
Explanation: useCallback for an event handler.
2 Produce value
To produce a value, use ____.
To produce a value, use useMemo.
Explanation: useMemo to produce a value.
3 Match useMemo and useCallback
| Term | Meaning |
|---|---|
useMemo |
value |
useCallback |
function |
deps |
dependencies |
cache |
cache |