React Foundations · Effects & Refs

Effect dependencies and cleanup

Effect dependencies and cleanup

Some effects start something that keeps running: a timer, a subscription, an event listener. If the component goes away and that work does not stop, it leaks — and the callback may fire against a component that is no longer on the screen.

An effect can return a cleanup function to undo its own setup:

useEffect(() => {
  document.title = 'mounted';

  return () => {
    document.title = 'unmounted';
  };
}, []);

React calls that cleanup in two moments:

  • before the effect runs again, when a dependency changed, and
  • when the component is removed from the screen (unmount).

The rule holds both ways: whatever the effect set up, the cleanup tears down. Clear the timer, remove the listener, close the subscription.

With an empty dependency array, the effect runs once on mount, so its cleanup runs once on unmount.

Your job is to clean up after an effect in App.jsx.

Challenge

When the component leaves the page, it leaves its title behind. Export an App component from App.jsx that sets document.title to mounted in an effect and returns a cleanup that sets it back to unmounted.

The Test renders your component, unmounts it, and expects document.title to be unmounted. The starter sets the title but returns no cleanup, so the Test fails.

App.jsx
import { useEffect } from 'react';

export function App() {
  useEffect(() => {
    document.title = 'mounted';
  }, []);

  return <h1>Hello</h1>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.