Unmounting is the lifecycle stage in which React removes a component from the rendered interface. Conditional rendering can repeatedly mount and unmount a component, discarding its local data each time. section 6.0 section 6.2.1
Use an effect cleanup function to stop timers, remove listeners, cancel work, or release other resources when the component disappears. An empty dependency array makes the effect and cleanup run only on mount and unmount, not ordinary re-renders. section 6.1.2 section 6.1.3
Unmounting commonly matters when a component:
- Stops an interval started when it mounted. section 6.1.2
- Cancels or ignores a slow data request before it updates removed state. section 6.1.2
- Restores keyboard focus after a dialog closes. section 6.1.3
- Records an analytics event when a dialog is dismissed. section 6.1.3
Stop a stopwatch on unmount
function Stopwatch() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval( () => setSeconds(s => s + 1), 1000 ); return () => clearInterval(interval); }, []); return <h1>Seconds: {seconds}</h1>; } function App() { const [showWatch, setShowWatch] = useState(false); return <> <button onClick={() => setShowWatch(b => !b)}>Toggle watch</button> {showWatch && <Stopwatch />} </>; } section 6.1.2
Figure 6.4 To make the effect hook activate with an effect and cleanup only on mount and unmount, respectively, you must add an empty dependency array to make sure that the effect and cleanup never runs just because the component is re-rendering.
Shows why an empty dependency array restricts the effect and cleanup to mounting and unmounting. section 6.1.2

