What is componentWillUnmount in Reactjs With Example

Today now In this blog i would like to talk with you about componentWillUnmount in react js. We know that componentWillUnmount is a method of component life cycle. So this method call before the component destroyed. So if we need to clean up anythings with regard this component then we can do in this method.

Now we should not call setState() in componentWillUnmount() because of the component will never be re-rendered. So Once a component instance is unmounted, then it will never be mounted again. So we can also call though api or event in this method.

componentWillUnmount() Example

/src/App.js file

import React from 'react';
import './App.css';
import User from './User';

class App extends React.Component{


    return (
      <div className="App">
        <header className="App-header">
            this.state.toggleUser ? <User /> : null
          <button onClick={()=>{this.setState({toggleUser:!this.state.toggleUser})}}>Delete User Info</button>


export default App;

/src/User.js file

import React from 'react'

class User extends React.Component{

        console.warn('componentWillUnmount call')
        alert('User has been deleted');       

        console.warn('render call')
                <h1>User Name : CodingsPoint</h1>
                <h1>User Email : CodingsPoint@gmail.com</h1>

export default User;

Read Also : How To Create Functional Component In React JS ?
I hope it will help you. Also you can follow us onĀ Facebook


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →