State를 직역하면 상태라는 뜻을 의미한다.
React에서의 state는 component의 상태 보다는 그의 변경 가능한 데이터를 표현한다.
다음 코드를 살펴보자.
import React, { useState } from 'react';
function Counter() {
// 'count'라는 state 변수와 'setCount'라는 state 함수를 정의
// 'count'의 초기 값을 0으로 설정
const [count, setCount] = useState(0);
return (
<div>
<h1>Counter: {count}</h1> {/* 현재 count를 출력 */}
<button onClick={() => setCount(count + 1)}>더하기</button> {/* count를 더함 */}
<button onClick={() => setCount(count - 1)}>빼기</button> {/* count를 뺌 */}
<button onClick={() => setCount(0)}>초기화</button> {/* count를 0으로 초기화 시킴 */}
</div>
);
}
export default Counter;
먼저 useState라는 hook을 사용해 function component에 count state 변수와 setCount라는 state 함수를 추가해줬다. (hook은 이후 글에서 자세히 설명할 예정이다)
useState(0)이라는 함수 사용을 살펴보면 state 변수인 count의 초기값을 0으로 지정해준 것이다.
Counter component의 return 값에서 <h1>태그 안에 count라는 state 변수를 쉽게 출력해준 것 처럼 쉽게 사용할 수 있다.
그 밑에 button들에서 setCount 함수가 어떻게 사용되는지 확인해보자.
state는 직접 수정/변경이 되면 안되며, 함수를 사용해 값을 변경해야한다.
이때 사용되는 함수가 set 함수이다.
setCount 함수가 호출될 때 Counter component는 다시 렌더링을 거쳐 UI에 표시 될 값을 업데이트한다.
Component도 인간과 같이 생명주기가 있다.
출생, 인생, 사망 세 단계를 거친다고 생각하면 쉽다.
이를 설명하기 위해 앞서 사용한 function component와 같은 기능을 하는 class component의 코드를 살펴보자.
Function component와 class component가 뭔지 모른다면 아래 글을 참고하자.
[React] Function component와 class component
import React from 'react';
class Counter extends React.Component {
constructor(props) {
super(props);
// State initialization
this.state = { count: 0 };
}
// Lifecycle method: componentDidMount
componentDidMount() {
console.log('Counter component mounted');
}
// Lifecycle method: componentDidUpdate
componentDidUpdate() {
console.log(`Component updated. New count: ${this.state.count}`);
}
// Lifecycle method: componentWillUnmount
componentWillUnmount() {
console.log('Component will unmount...');
}
// count 더하기
increase = () => {
this.setState({ count: this.state.count + 1 });
}
// count 빼기
decrease = () => {
this.setState({ count: this.state.count - 1 });
}
// count 초기화
reset = () => {
this.setState({ count: 0 });
}
render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={this.increase}>더하기</button>
<button onClick={this.decrease}>빼기</button>
<button onClick={this.reset}>초기화</button>
</div>
);
}
}
export default Counter;
여기에서는 앞에 코드 예제에서는 볼 수 없었던 생명주기 함수들이 있다:
componentDidMount()componentDidUpdate()componentWillUnmount()componentDidMount에서 설정된 event listner를 삭제하는 역할을 한다.