AI Hints
Home›React Tutorial›Effects
React · Lesson 39 of 120

Cleanup

Timers and listeners.

⏱ 2 min read▶ Video at 30:50🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Some effects start something that keeps going, like a timer. When the component goes away, it should stop. An effect can return a cleanup function, and React calls it at the right time.

  • Effects that keep going
  • Must stop
  • Return a cleanup

A sale countdown

The effect starts an interval that ticks every second. It returns a function that clears the interval. When we hide the countdown, React runs that cleanup, and the ticking stops. We wait, then hide it. Run it.

App.jsxjsx
import { useState, useEffect } from "react";
function Countdown() {
  const [left, setLeft] = useState(10);
  useEffect(() => {
    const id = setInterval(() => setLeft(s => s - 1), 1000);
    console.log("timer started");
    return () => { clearInterval(id); console.log("timer cleared"); };
  }, []);
  return <p className="big">{left}</p>;
}
export default function App() {
  const [show, setShow] = useState(true);
  return (
    <div><h2>Flash sale ends in</h2>
      {show && <Countdown />}
      <button id="hide" onClick={() => setShow(false)}>Hide</button></div>
  );
}
Output
timer started
timer cleared
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"wait": 3200}, {"click": "#hide"}]

Things to clean up

Clear timers and intervals. Remove event listeners you added to the window. Close connections, like web sockets. If an effect starts it, the cleanup stops it.

keyvalue
setIntervalclearInterval
addEventListenerremoveEventListener
Connectionsclose them
Rulestart, then stop

Summary

Return a cleanup function from effects that start timers, listeners, or connections. Next, fetching data.

Key takeaways
  • return () => ...
  • Clear timers
  • Remove listeners
Next up: Fetching Data — loading and errors