liveBook · Manning

Unmounting

As explained in React Quickly, Second Edition

Unmounting is the lifecycle stage in which a React component is removed from the rendered interface.

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.
06-04

Shows why an empty dependency array restricts the effect and cleanup to mounting and unmounting. section 6.1.2

How React Quickly, Second Edition covers it

How deep it goes
Explains conditional unmounting, empty dependency arrays, cleanup functions, and request cancellation through runnable examples.
Examples
Demonstrates stopwatches, remote dropdowns, dialogs, analytics events, focus restoration, abort controllers, and mounted guards.
What it assumes
Introduces mounting, unmounting, rendering, effects, and lifecycle terminology alongside JSX and functional components.
What you can do after
Apply it via useEffect cleanup to release resources and prevent removed components from receiving unfinished asynchronous updates.
How it connects
Connects unmounting with React component lifecycle, useEffect, cleanup functions, conditional rendering, timers, event listeners, and data fetching.

Also explained in

Compare how 2 books explain unmounting →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.