Home React 08. State와 Props
Post
Cancel

React 08. State와 Props

What is the difference between state and props?

State와 Props는 어떻게 다른가? state와 props는 둘 다 Javascript 객체이다. props는 component에 전달되는 객체이며 (함수 매개변수와 유사), state는 component 내부에서 관리되는 객체 (함수 내에 선언된 변수와 유사) 이다.

Why is setState giving me the wrong value?

리액트에서 this.props와 this.state는 둘 다 렌더링된 값을 나타낸다. props는 상위 컴포넌트에서 전달받은 값이지만 state는 컴포넌트 내부에서 관리되기 때문에 해당 컴포넌트에서 변경할 수 있다. 주의할 점은 setState는 비동기(asynchronous)적으로 동작하기 때문에 새로운 값이 즉시 반영되게 코드를 작성해서는 안된다.

1
2
3
4
5
6
7
8
9
    incrementCount() {
        this.setState({count: this.state.count + 1});
    }

    handleSomething() {
        this.incrementCount();
        this.incrementCount();
        this.incrementCount();
    }

this.state.count가 0에서 시작한다고 생각하자. state값 변경으로 컴포넌트가 리렌더링 될 때, 우리의 기대와 달리 this.state.count는 1로 렌더링 될 것이다. 리액트는 컴포넌트를 리렌더링할 때 까지 this.state.count를 업데이트 하지 않는다. 그래서 this.incrementCount()는 항상 0을 받아 1로 변경하게 된다.

How do I update state with values that depend on the current state?

그래서 어떻게 고칠껀데?? setState 호출이 항상 최신 버전의 상태를 사용하도록 하기위해 객체 대신 함수를 전달하면 된다.

1
2
3
4
5
6
7
8
9
10
11
    incrementCount() {
        this.setState((state) => {
            return { count: state.count + 1 }
        });
    }

    handleSomething() {
        this.incrementCount();
        this.incrementCount();
        this.incrementCount();
    }

When is setState asynchronous?

setState는 이벤트 핸들러 내부에서 비동기적이다. 예를 들어 부모와 자식 모두 이벤트 중 setState를 호출할 경우 자식은 두번 리렌더링되지 않는다. 대신 이벤트가 끝날 때 state 업데이트를 flushed 한다.

Why doesn’t React update this.state synchronously?

왜 리액트는 업데이트를 동기적으로 하지 않는가? 리액트는 의도적으로 모든 컴포넌트의 setState()가 호출될 때 까지 기다린다. 결론적으로 퍼포먼스를 향상시키기 위해 불필요한 리렌더링을 피하는 것이다.

This post is licensed under CC BY 4.0 by the author.