본문 바로가기

Programming/React ; Redux

State 특성 3가지

React에는 Props, State라는 2가지 데이터 모델이 있다.  이 글은 State의 특성에 대한 설명이다.


1. state는 수정할 수 없다. (불변성)

 state는 아래와 같이 접근하여 수정할 수 없다. 

this.state.counter = 3; (X)
this.state.counter = this.state.counter+this.props.increment; (X)
this.state.counter = this.state.counter++; (X)

반드시 setState로 접근하여 수정해야 한다. 

setState({counter:3}); (O)
setState((state, props) => { state.counter + props.increment }); (O)
setState((state) => { state.counter + 1 }); (O)

 

2. setState()는 비동기로 동작한다. 

아래와 같이 값을 수정하면 오류가 발생할 수 있다. this.state, this.props는 setState이 실행되기 직전 값을 참조하기 때문이다.

setState({counter : this.state.counter + this.props.increment}); (X)

callback을 사용해서 state, props를 호출해야 setState에 의해 순차적으로 변경된 값을 참조할 수 있다. 

(event loop 큐에서 값을 하나씩 shift() 받아오기 때문에!)

setState((state, props) => { state.counter + props.increment }); (O)

 

3. state는 병합된다. 

setState()를 호출할 때 React는 제공한 객체를 현재 state에 병합한다. 

  constructor(props) {
    super(props);
    // counter, flag 속성을 가지고 있다.
    this.state = { counter: 0, flag: "increase" }; 
    this.increase = this.increase.bind(this);
    this.decrease = this.decrease.bind(this);
  }

  increase() {
    // state에 counter 변경사항을 병합한다.
    this.setState((state, props) => ({
      counter: state.counter + props.increment
    }));
  }

  decrease() {
    // state에 counter 변경사항을 병합한다.
    this.setState((state, props) => ({
      counter: state.counter - props.decrement
    }));
  }

 

 

 

본 글에서 인용한 전체 코드는 아래 글에서 볼 수 있다.

2021.05.21 - [Programming/React ; Redux] - Clock Timer 컴포넌트 사례로 보는 생명주기 작성 방법

 

Clock Timer 컴포넌트 사례로 보는 생명주기 작성 방법

동일한 코드를 Class형, 함수형으로 나누어서 작성했다. Class형 작성 import React from "react"; export default class Clock extends React.Component { // 생성자 // state 초기화 constructor(props) { super..

kimyejin.tistory.com

 

 

 

Reference. 

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

'Programming > React ; Redux' 카테고리의 다른 글

React로 사고하기  (0) 2021.05.22
JSX란?  (0) 2021.05.21
React/Redux - 실수 모음집 (누적 중)  (0) 2021.05.15
React.memo 사용 예제  (0) 2021.05.10
React Async 사용하기 - 1. useAsync, Helper components  (0) 2021.05.09