useEffect and fetching data
Rendering should be pure: calculate the UI from props and state, nothing else. But apps also need side effects: fetching data, subscribing to events, timers, updating the document title. useEffect runs code after React has updated the screen, to sync your component with something outside React.
The basics
The dependency array
| You write | The effect runs… |
|---|---|
useEffect(fn) |
After every render (rarely what you want) |
useEffect(fn, []) |
Once, after the first render (when the component "mounts") |
useEffect(fn, [a, b]) |
After the first render and whenever a or b changes |
Include every value from your component that the effect uses. The ESLint plugin
react-hooks/exhaustive-depschecks this for you.
Cleanup functions
If your effect starts something (a timer, a subscription, an event listener), return a function that stops it. React calls the cleanup before re-running the effect and when the component is removed:
Without cleanup, removing the stopwatch would leave the timer running forever: a memory leak.
Why does the effect run twice in development? In Strict Mode, React deliberately mounts, unmounts and re-mounts components in development, to surface missing cleanups. It doesn't happen in production.
Syncing with the browser
Fetching data
The classic pattern tracks loading, error and data, and ignores stale responses:
Click quickly between users. The ignore flag ensures that a slow, old response can never overwrite a newer one.
You might not need an effect
Effects are for syncing with external systems. Many beginners overuse them:
| ✗ Don't use an effect to… | ✓ Instead |
|---|---|
Compute a value from props or state (fullName from first + last) |
Calculate it during render: const fullName = first + ' ' + last |
| Respond to a click or submit | Put the code in the event handler |
| Reset state when a prop changes | Give the component a key that changes |
| Fetch data in a large app | Use a data library (TanStack Query, SWR) or your framework's data fetching (Next.js Server Components) |
Practice: live search
Build a search box over the list below. Wait 300 ms after the user stops typing before filtering (a "debounce", using setTimeout in an effect with a cleanup), and show "Searching…" while you wait.
1.When does useEffect(fn, []) run?
2.Why return a cleanup function from an effect that starts a timer?