useEffect Effect Hook
Last updated: 2026-11-02
useEffect Effect Hook
useEffect is the declarative home for side effects — data fetching, subscriptions, timers, direct DOM work. It runs after render, and a returned cleanup function runs before the next effect and on unmount.
| Group | Effects & Performance |
|---|---|
| Kind | Hook |
| Since | React 16.8 |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
useEffect(() => {
// side effect
return () => { /* cleanup */ }
}, [deps]) // [] mount-only; [a, b] on changes; omit = every render
⚙️ Parameters
| effect function | The effect body, run after render. May return a cleanup function. |
|---|---|
| deps (optional dependency array) | Controls timing: [] runs once after mount; [a, b] re-runs when any changes; omitting re-runs after every render. |
Returns:Nothing. Return a cleanup function from the effect when teardown is needed.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
Shows "Running for 0s" and increments every second; the interval is cleaned up on unmount — no leaks.
💡 Key Points
💡 Tip Every setInterval / addEventListener / subscription almost always needs a cleanup — or it keeps running after unmount.
⚠️ Warning Missing object/function deps is the #1 bug source: fresh references every render make the effect re-run endlessly.
ℹ️ Info [] means "mount-related only" — think twice before silencing the exhaustive-deps lint warning.
🏷️ More Effects & Performance
💡 Related Cases
More case studies coming soon.
📚 Related Tutorials
❓ FAQ
Q What is the relationship between useEffect and the lifecycle methods?
A One useEffect (with cleanup) covers componentDidMount, componentDidUpdate and componentWillUnmount at once — think in terms of dependencies changing, not lifecycle phases.
Q Why does my useEffect loop forever?
A Usually an object/function dep recreated every render, or setState of a value the effect depends on. See the Effect Pitfalls entry.
Q When does the cleanup function run?
A Twice: right before the next effect run (clean old, then run new), and on unmount.