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.

GroupEffects & Performance
KindHook
SinceReact 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 functionThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏