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{ 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 : CodingsPoint</h1> <h1>User Email : CodingsPoint@gmail.com</h1> </div> ) } } 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