210322 개발일지(105일차) - React State 올바르게 사용하기

고재개발·2021년 3월 23일
0

React Study

목록 보기
5/10

React의 Class에서 state를 사용할 때는 아래와 같은 3가지를 유의해야 한다.

  1. 직접 state 값을 수정하면 안된다. (setState 함수 사용)
  2. state 업데이트는 비동기적이다.
  3. state의 업데이트는 병합된다? (state의 변수가 여러 개라면, 따로 업데이트가 가능)

1. 직접 state 값을 수정하면 안된다. (setState 함수 사용)

만약 아래와 같이 state를 수정하면, 수정 값은 반영되나 컴퍼넌트를 다시 렌더링하지는 않는다. 즉, 올바른 사용법이 아니다.

// Wrong
this.state.comment = 'Hello';

대신 setState() 함수를 사용해야 한다.

// Correct
this.setState({comment: 'Hello'});

2. state 업데이트는 비동기적이다.

setState()를 사용할 때, 이 함수는 바로 값을 업데이트하지 않을 수 있다. (앞에 작업들이 밀려있는 이유 등)
그래서, 아래와 같이 사용하면 엉뚱한 값이 나타날 수 있다.

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

그래서, 아래와 같이 함수를 인자로 사용해야 원하는 시점의 값을 제대로 받아들인다.

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

3. state의 업데이트는 병합된다? (state의 변수가 여러 개라면, 따로 업데이트가 가능)

아래와 같이 state는 여러 독립 변수가 있을 수 있다. 또한, 이 여러 state안의 변수를 따로 업데이트 할 수 있다.

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

위와 같은 state가 있을 때, 아래 처럼 별도의 setState() 함수를 활용하여 독립적으로 각 state안의 변수를 업데이트 할 수 있다.

  componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }

출처 : React 공식 페이지

profile
고재개발

0개의 댓글