What is componentWillUnmount in Reactjs With Example

React.js

Nicesnippets

21234

22-01-2020


In this blog i would like to explain about componentWillUnmount in react js. componentWillUnmount is a method of component life cycle. this method call before component destroyed. if you need to clean up anythings with regard this component you can do in this method.

You should not call setState() in componentWillUnmount() because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again. you can also call 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{

constructor(){

super();

this.state={

toggleUser:true

}

}

render(){

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>

</header>

</div>

);

}

}

export default App;

/src/User.js file

import React from 'react'

class User extends React.Component{

componentWillUnmount(){

console.warn('componentWillUnmount call')

alert('User has been deleted');

}

render(){

console.warn('render call')

return(

<div>

<h1>User Name : nicesnippets</h1>

<h1>User Email : nicesnippets@gmail.com</h1>

</div>

)

}

}

export default User;

I hope it can help you...


Recommended Posts