ReactJS Component Lifecycle Mounting

ReactJS Component Lifecycle Mounting

ReactJS mounting have 3 methods:
- getInitialState(): object is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
- componentWillMount(): is invoked immediately before mounting occurs.
- componentDidMount(): is invoked immediately after mounting occurs. Initialization that requires DOM nodes 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
<!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');
      }
    });

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

    ReactDOM.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.

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