Cleanup Function Effect Cleanup

Last updated: 2026-11-02

Cleanup Function Effect Cleanup

The cleanup function is the teardown returned by an effect: it runs once before the next run of that effect and once more when the component unmounts, and it is what cancels timers, unsubscribes listeners and aborts in-flight requests. Without a cleanup, the side effect keeps running after the component is gone and leaks. The rule of thumb is simple: anything you start inside an effect and do not finish synchronously needs a matching cleanup.

GroupEffects & Performance
KindPattern

ℹ️ 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(() => {
  const id = setInterval(tick, 1000)
  window.addEventListener('resize', onResize)
  return () => {                    // teardown: clear the old one before running the new one
    clearInterval(id)
    window.removeEventListener('resize', onResize)
  }
}, [])

Returns:No return value; this entry describes an encoding pattern rather than a function.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

The timer adds one second every second; clicking "Pause" stops it immediately (the cleanup function runs), clicking "Resume" starts it again, and at any moment only one timer is alive.

💡 Key Points

⚠️ Warning When the dependencies change, React runs the previous cleanup before running the new effect — without understanding this you cannot explain the "the timer runs faster and faster" bug.
💡 Tip setInterval, addEventListener, event subscriptions and unfinished fetches should all have a cleanup function.
ℹ️ Info "Clear the old one first, then create the new one" guarantees that only one copy of a side effect is alive at any time.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q Must every effect return a cleanup function?
A No. An effect that owns nothing to tear down (a pure log, for example) can skip it; with timers, subscriptions or requests it is required.
Q Does the cleanup run when the dependencies change?
A Yes. Every time the effect re-runs, the previous cleanup runs first; the last cleanup runs when the component unmounts.
Q Does the cleanup function read the new state or the old state?
A The old state — a cleanup closes over the render that created it, which is exactly what cancelling the old side effect requires.
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%

🙏 帮我们做得更好

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

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