TechnicalHard React
When should you use useMemo and useCallback, and when are they unnecessary?
Asked for Frontend Developer, Full-Stack Developer
Why they ask this: Separates candidates who understand rendering performance from those who memoise everything by habit.
Answer
useMemo(fn, deps)caches a computed value untildepschange.useCallback(fn, deps)caches a function reference untildepschange. It is the same asuseMemo(() => fn, deps).
Use them when:
- A calculation is genuinely expensive, such as filtering or sorting thousands of rows.
- You pass an object or function to a child wrapped in
React.memo, and a new reference every render would defeat it. - The value is a dependency of another hook (
useEffect) and a new reference would re-run it every render.
jsx
const visibleJobs = useMemo(
() => jobs.filter((j) => j.title.toLowerCase().includes(query.toLowerCase())),
[jobs, query],
);
const handleSelect = useCallback((id) => setSelected(id), []);Skip them for cheap calculations and for handlers passed to plain DOM elements. Memoisation itself costs memory and comparisons, so measure with the React DevTools Profiler before you optimise. (React Compiler can add this memoisation automatically in projects that use it.)
Can you explain this in your own words?