본문 바로가기
What I Learned/React JS

React JS - State & Lifecycle

by 단풍국범생이 2021. 2. 24.

Why use class components instead of function components?
- To use "state"

class App extends React.Component{
  state = {
  }
  render(){    
    return <div></div>
  }
}

React automatically execute the render method inside of the class component.

A state is an object. The data can be change (dynamic data).

      <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>

If you write "this.add()", the method will be executed immediately, not when it's clicked.

1) this.setState({ count: this.state.count -1 });
2) this.setState(current => ({ count: current.count -1 }));

Do not change the state directly. The reason is that the render is not being called when the state has changed.
So, use the "setState" method instead. This is re-render with a new state. It is not a good practice to use the current state directly. So, like the second example, use the "current" keyword to call the state.

 

React Life Cycle:

  componentDidMount(){
    console.log("Component rendered");
  }
  componentDidUpdate(){
    console.log("Componenent updated");
  }
  componentWillUnmount(){
    console.log("Component unmounted");
  }

1. Mounting - componentDidMount()

2. Updating - componentDidUpdate()

3. Unmounting - componentWillUnmount()

'What I Learned > React JS' 카테고리의 다른 글

Learning React.js  (0) 2021.03.08
React JS - JSX & Props  (0) 2021.02.23
How to start React JS Project?  (0) 2021.02.23