React · Lesson 7 of 7
Effects with useEffect
Running side effects — timers, data loading, subscriptions — and cleaning up.
Rendering should be pure: given the same props and state, return the same JSX. Work that reaches outside the component — fetching data, timers, subscriptions, changing the document title — belongs in an effect.
React.useEffect(() => {
// runs after render
return () => { /* cleanup */ };
}, [dependencies]);
[]— run once after the first render.[city]— run again whenevercitychanges.- Return a cleanup function to stop timers or ignore stale responses.
In real apps, data loading is often handled by a framework or a library (React Query, SWR, Next.js), but understanding effects is essential for interviews. The example simulates a slow API with setTimeout.
Try it yourself
Edit the code and press Run (or Ctrl/⌘ + Enter). Code runs only in your browser, in a sandbox.
Key points
- Effects are for side effects, not for computing values.
- The dependency array controls when it re-runs.
- Clean up timers, subscriptions and stale requests.
Quick check
When does an effect with an empty dependency array run?
[] means no dependencies change, so it runs after the first render (its cleanup runs on unmount).
Practice task
Write a Clock component that shows the current time and updates every second, clearing the interval on cleanup.
Interview corner
Why might an effect run twice in development?
React's Strict Mode mounts, unmounts and remounts components in development to expose effects that are missing a cleanup.
What happens if you forget a dependency?
The effect captures stale values and won't re-run when that value changes. The eslint-plugin-react-hooks rule helps catch this.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.