React `componentWillUnmount`

`componentWillUnmount()` runs immediately before a React class component is removed. Use it to clean up resources the component started, such as timers, subscriptions, and event listeners.

`componentWillUnmount()` is a lifecycle method for React class components. React calls it immediately before the component is removed from the UI. It takes no arguments and should not return a value.

Use it to undo work started by the component, such as clearing a timer, removing an event listener, closing a connection, or unsubscribing from an external source. Cleanup helps prevent stale callbacks and resources that outlive the component.

Pair setup and cleanup deliberately: remember the timer ID, unsubscribe function, or exact listener used during setup, then release that resource here. If props or state changes require replacing a resource while the component remains mounted, handle that transition in `componentDidUpdate` as well; unmount cleanup alone is not enough.

In development Strict Mode, React may run a mount, unmount, and mount sequence to expose incomplete cleanup. Class components remain supported, though React generally recommends function components for new code. For many function-component use cases, an effect cleanup is the corresponding pattern.

Key points

Interview questions

When does `componentWillUnmount` run, and what is it for?

It is called just before React removes a class component from the UI. Use it to release resources or undo external work started by the component, such as subscriptions, timers, or listeners. It is not called during server rendering.

How would you prevent a timer from continuing after a component is removed?

Store the identifier returned by `setInterval` when setting it up, then pass that identifier to `clearInterval` during unmount. This stops future callbacks after the component is gone. If the interval's configuration can change while mounted, update or replace it in `componentDidUpdate` too.

How do you design lifecycle cleanup when an external connection depends on changing props?

The lifecycle method should reverse or release external work that the class owns, using the corresponding handle or cleanup function. Cleanup should be safe for the resource's current state and should not assume an update lifecycle always ran first. For resources that depend on changing props, compare current and previous values in `componentDidUpdate` and replace the resource when needed.

Why might `componentWillUnmount` run soon after mounting in development?

React calls `componentWillUnmount` during the development Strict Mode lifecycle check after mounting, then mounts the component again. This is intended to expose setup that is not properly undone. Cleanup should therefore correctly release what that setup created and should not rely on unmount happening only once over the application's lifetime.