The browser and React · Question 12 of 50
useEffect, useMemo, useCallback: when do you use each?
Whether you understand hooks, and avoid optimising for nothing.
The answer
useEffect is for side effects that keep something outside React in sync: a subscription, a timer, a fetch, the page title. It runs after render whenever its dependencies change, and its cleanup runs before the next run and on unmount.
useMemo keeps a computed value between renders until its dependencies change: for genuinely expensive work, or to keep an object's reference stable. useCallback is the same for functions, so a memoised child or an effect does not see a new function on every render. Without a measured reason, skip the last two: they have a cost of their own.
useEffect(() => {
const id = setInterval(tick, 1000)
return () => clearInterval(id) // cleanup
}, [])
const sorted = useMemo(() => sortBig(list), [list])
const onSave = useCallback(() => save(id), [id])The picture
useEffect DO something after render (sync with the outside) useMemo REMEMBER a value until the deps change useCallback REMEMBER a function until the deps change
What is a stale closure?
Show the answer
An effect or callback sees the state from the render it was created in. If its dependencies leave that state out, it keeps reading the old value. Fix the dependencies, or use the functional update setCount((c) => c + 1).