How does useEffect work in React and what is the dependency array?
Quick answer
useEffect runs a function after the component renders; the dependency array tells React when to re-run it: with no array it runs after every render, with an empty array only after the first, and with values only when those values change.
Effects are for synchronising your component with something outside React, such as subscriptions, timers, network requests or the document title. The function you return from an effect is the cleanup, and React runs it before the next run of the effect and when the component unmounts.
Every value from the component that the effect uses should be listed in the dependency array, otherwise the effect works with stale values. In development with Strict Mode, React deliberately mounts, unmounts and re-mounts components once to help you find missing cleanup. Do not use effects for things you can calculate during render or handle in an event handler.
useEffect(() => {
const controller = new AbortController();
fetch("/api/users/" + userId, { signal: controller.signal })
.then(r => r.json())
.then(setUser)
.catch(err => { if (err.name !== "AbortError") setError(err); });
return () => controller.abort(); // cleanup when userId changes or unmounts
}, [userId]);Key points
- No array: every render. [] : once. [a, b]: when a or b change
- Return a function to clean up
- Do not use effects for derived data or user-triggered actions
Questions interviewers ask next
- Why does my useEffect run twice in development?
- What causes an infinite loop in useEffect?