defaultK

[React] State 와 LifeCycle 본문

React

[React] State 와 LifeCycle

kwoss2341 2022. 7. 17. 14:19

https://ko.reactjs.org/docs/state-and-lifecycle.html

 

State and Lifecycle – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

State

✔ 리액트 컴포넌트의 변경 가능 데이터

✔ state가 변경될 경우 재랜더링.

✔ 변경시 재랜더링이 일어나므로 성능을 고려하여 state 값 설정

✔ state값을 변경시

-Class component : setState() 

-Function component : useState() 훅에서 정의한 set함수 

 

 

 

LifeCycle

✔ componentDidMount()

- 컴포넌트가 생성될 때

 

✔ componentDidUpdate()

- component props가 변경될 때

- state값 변경시(setState())

- forceUpdate() 강제 업데이트 함수 호출 시

 

✔ componentWillUnmount()

- 컴포넌트가 언마운트될때 호출

 

 

 

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

 

'React' 카테고리의 다른 글

[React] Hook 훅  (0) 2022.07.17
Comments