1. Concept library
  2. Web Dev with React
  3. Module 5: Effects and data fetching

Concept

useEffect and cleanup

useEffect runs code after render to synchronise with something outside React: a subscription, a timer, the document title. Returning a function from it cleans up before the next run and on unmount.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what useEffect is for and when it runs
  2. Write an effect with a cleanup for a subscription or timer
  3. Spot the dependency left out and explain the stale value it causes

In practice

A few lines that show useEffect and cleanup doing its job.

TSX
function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const onResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  return width;
}

The common mistake

Watch for

Leaving a value out of the dependency array to stop the effect re-running. The effect then uses a stale value from an old render. Fix the cause: move the value inside, or make the effect not need it.

What to know first

Your roadmap puts these before useEffect and cleanup, unless you already know them.

How it stays learned

Once a session shows you understand useEffect and cleanup, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on useEffect and cleanup.