Mark As Completed Discussion

Component Unmounting

In React, the component unmounting phase occurs when a component is being removed or destroyed from the DOM. During this phase, the component is no longer needed and any clean-up tasks can be performed.

The method invoked when a component is being unmounted is componentWillUnmount(). This method allows you to perform any necessary clean-up operations before the component is removed from the DOM.

For example, if your component has set up any event listeners or timers, you can use the componentWillUnmount() method to remove those listeners or clear the timers to prevent memory leaks.

Here's an example that demonstrates the usage of componentWillUnmount():

JAVASCRIPT
1// Example of component unmounting
2
3class Timer extends React.Component {
4  constructor() {
5    super();
6    this.state = {
7      time: 0
8    };
9    this.intervalId = null;
10  }
11
12  componentDidMount() {
13    // Start the timer
14    this.intervalId = setInterval(() => {
15      this.setState(prevState => ({
16        time: prevState.time + 1
17      }));
18    }, 1000);
19  }
20
21  componentWillUnmount() {
22    // Clean up the timer
23    clearInterval(this.intervalId);
24  }
25
26  render() {
27    return (
28      <div>
29        <h1>Timer: {this.state.time}</h1>
30      </div>
31    );
32  }
33}