state는 props와 매우 비슷해 보이지만 다르다.
props는 리액트가 렌더링함수를 실행할 때 해당 컴포넌트의 인스턴스를 만나면 같이 작성된 Attribute를 props 객체에 담아서 컴포넌트의 생성자를 실행한다. 즉, 외부에서 받아온 데이터들을 props라는 객체에 담는다.
반면에 state는 props로 받아온 데이터를 이용해서 초기화 할 수도 있지만 컴포넌트 내부에서 새롭게 초기화 하는 것을 가능토록 한다. state 에 컴포넌트 내부에서만 사용될 변수(필드)를 추가해서 사용하면 된다. 또, state를 컴포넌트 렌더링 메서드에서 호출하는 다른 컴포넌트에 넘겨줄 수도 있다. (이것은 props도 마찬가지)
state의 프로퍼티의 값을 바꾸기 위한 메서드이다.
state의 값을 직접적으로 변경하면 React는 변화를 인지하지 못해서 원하는대로 렌더링이 일어나지 않는다.
setState()를 통해 state 프로퍼티의 값을 변경하면 React는 state 변경을 인지하고 virtualDOM과 실제 DOM을 비교해서 업데이트가 필요한 부분을 찾아서 업데이트한다.
즉, setState()를 사용하지 않으면 state의 변경을 React에게 알리지 않는 것과 같다. (다른 방법이 존재할까? -> 공부하면서 발견하면 수정해야함)
-> SetState()를 통해서 state를 업데이트하자!
[[setState()]]
말그대로 컴포넌트의 lifecycle과 관련된 메서드이다.
componentDidMount()
: React가 컴포넌트의 constructor를 실행하고 render 메서드를 실행한 후에 실행하는 메서드componentWillUnmount()
: instance of Component 와 매칭되는 DOM node가 삭제되었을 때 실행하는 메서드 ( instance of Component 와 관련된 resource들을 모두 제거하는 청소부 역할을 하는 메서드이다. )[[lifeCycle Method]]
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>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />); // 실행
this.timerId
를 하는 이유는 추후에 DOM node가 삭제되는 경우를 고려했기 때문이다. 삭제할 때 관련된 모든 resource를 free 시켜줘야하는데 (해제) 그때 this.timerId를 이용해서 제거할 수 있음.Component Constructor -> render -> (DOM node 생성) -> componentDidMount -> ••• -> (DOM node 삭제) -> componentWillUnmount
#리액트#