EN
React - componentDidMount and componentWillUnmount (class component)
0
points
In this article, we would like to show you how to handle mount and unmount events in React working with class components.
In React class components we can handle mount or unmount actions with two methods:
componentDidMount()
- that gets invoked right after a React component has been mounted (right after the firstrender()
),componentWillUnmount()
- the last function called immediately before the component is removed from the DOM.
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
componentDidMount() {
console.log('MyComponent onMount');
}
componentWillUnmount() {
console.log('MyComponent onUnmount');
}
render() {
return (
<p>MyComponent</p>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
}
}
render() {
return (
<div>
<button onClick={() => this.setState({ visible: true })}>
Mount MyComponent
</button>
<button onClick={() => this.setState({ visible: false })}>
Unmount MyComponent
</button>
{this.state.visible && <MyComponent />}
</div>
);
}
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.