React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
Why should not call setState in componentWillUnmount?
You should not call setState() in componentWillUnmount() because once a component instance is unmounted, it will never be mounted again.
Code Example
tsx
import React, { Component } from 'react';
class TimerListener extends Component {
private timerId: any = null;
componentDidMount() {
this.timerId = setInterval(() => {
this.forceUpdate();
}, 1000);
}
componentWillUnmount() {
// ❌ NEVER call setState here: component is already unmounted,
// so no re-render occurs and React flags a memory leak.
// this.setState({ active: false });
// ✅ Clean up resources, intervals, subscriptions, and sockets:
clearInterval(this.timerId);
}
render() {
return <div>Active Timer</div>;
}
}