🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Expert Masterclasses.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEreact

react Documentation

LOADING ENGINE...

React ComponentWillUnmount

Master React components, hooks, and best practices.

ComponentWillUnmount

Author

Pascual Vila

Frontend Instructor.

componentWillUnmount is a lifecycle method of class components in React. It runs before the component is removed from the DOM. It is useful for cleaning up subscriptions or canceling background tasks such as API requests or intervals.

Example of componentWillUnmount:

          {`import React, { Component } from "react";
          
          class Clock extends Component {
            constructor(props) {
              super(props);
              this.state = { time: new Date().toLocaleTimeString() };
            }
            
            componentDidMount() {
              this.intervalId = setInterval(() => {
                this.setState({ time: new Date().toLocaleTimeString() });
              }, 1000);
            }
            
            componentWillUnmount() {
              clearInterval(this.intervalId);
            }
            
            render() {
              return <h1>{this.state.time}</h1>;
            }
          }
          
          export default Clock;`}