비교
특징 |
useState |
useReducer |
복잡도 |
간단한 상태에 적합 |
복잡한 상태 트랜지션에 적합 |
상태 갱신 방식 |
직접 상태를 업데이트 (setState) |
액션과 리듀서 함수로 상태 관리 |
코드 구조 |
코드가 짧고 간단 |
리듀서를 별도 정의하여 구조화 가능 |
공유 상태 관리 |
상태 공유가 쉽지 않음 |
Context와 함께 사용해 확장 가능 |
성능 |
단순한 컴포넌트에 적합 |
큰 상태나 복잡한 로직 처리에 적합 |
어떤 상황에서 사용할까?
- useState
- 상태가 단순하고 한두 개의 값만 관리하면 충분한 경우.
- 로컬 상태 관리.
- useReducer
- 상태가 복잡하거나 여러 액션 타입을 처리해야 하는 경우.
- 상태 업데이트 로직을 모듈화하거나 구조화하려는 경우.
- Context API와 함께 글로벌 상태 관리가 필요한 경우.
useState 예시
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
useReducer 예시
import React, { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
throw new Error("Unhandled action");
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>Increment</button>
<button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>
</div>
);
}