ReactJS Component Lifecycle Unmounting

ReactJS Component Lifecycle Unmounting

ReactJS mounting have 1 methods:
- componentWillUnmount(): is invoked immediately before a component is unmounted and destroyed. Cleanup should go here.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var Button = React.createClass({
      getInitialState: function() {
        return {
          val: 0
        }
      },
      handleUpdate: function() {
        this.setState({val: this.state.val + 1}
        );
      },
      componentWillMount: function() {
        console.log('mounting');
      },
      render: function() {
        console.log('rendering');
        return (
          <div>
            <button onClick={this.handleUpdate}>{this.state.val}</button>
          </div>
        );
      },
      componentDidMount: function() {
        console.log('mounted');
      },
      componentWillUnmount: function() {
        console.log('bye!');
      }
    });

    var App = React.createClass({
      handleMount: function() {
        React.render(<Button />, document.getElementById('app'));
      },
      handleUnmount: function() {
        React.unmountComponentAtNode(document.getElementById('app'));
      },
      render: function() {
        return(
          <div>
            <button onClick={this.handleMount}>Mount</button>
            <button onClick={this.handleUnmount}>Unmount</button>
            <div id="app"></div>
          </div>
        );
      }
    });

    React.render(<App />, document.body);
  </script>
</body>
</html>

In Button component getInitialState() method initial val: 0 by default.

When you click on Mount button, componentWillMount() method is invoked immediately before mounting occurs, and render() method render button into body DOM, and then componentDidMount() method is invoked immediately after mounting occurs.

When you click on Unmount button, componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.

So far go good, That’s it!!! See ya!!! :)