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:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
class MyComponent extends React.Component {
6
componentDidMount() {
7
console.log('MyComponent onMount');
8
}
9
10
componentWillUnmount() {
11
console.log('MyComponent onUnmount');
12
}
13
14
render() {
15
return (
16
<p>MyComponent</p>
17
);
18
}
19
}
20
21
class App extends React.Component {
22
constructor(props) {
23
super(props);
24
this.state = {
25
visible: true
26
}
27
}
28
29
render() {
30
return (
31
<div>
32
<button onClick={() => this.setState({ visible: true })}>
33
Mount MyComponent
34
</button>
35
<button onClick={() => this.setState({ visible: false })}>
36
Unmount MyComponent
37
</button>
38
{this.state.visible && <MyComponent />}
39
</div>
40
);
41
}
42
}
43
44
const root = document.querySelector('#root');
45
ReactDOM.render(<App />, root);
Note:
Go to this article to see functional component example.