useReducer: 복잡한 상태관리 훅
useReducer란 무엇인가?
useReducer는 React에서 제공하는 강력한 상태 관리 훅으로, 복잡한 상태 로직을 컴포넌트 외부로 분리할 수 있게 해주는 도구
기본 개념 이해하기
const [state, dispatch] = useReducer(reducer, initialState);
state: 현재 상태 값
dispatch: 상태를 변경하는 함수
reducer: 상태 변경 로직을 정의하는 함수
initialState: 초기 상태 값
간단한 카운터 예제로 살펴보기
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</>
);
}
useState vs useReducer
useState
- 간단한 상태 관리에 적합
- 상태 변경 로직이 간단할 때 사용
useReducer
- 복잡한 상태 관리에 최적
- 상태 변경 로직이 많고 복잡할 때 유용
- 상태 로직을 컴포넌트에서 분리 가능
복잡한 상태 관리 예시
const INIT_STATE = {
isLoading: false,
isSuccess: false,
isFail: false,
};
const ACTION_TYPE = {
FETCH_LOADING: "FETCH_LOADING",
FETCH_SUCCESS: "FETCH_SUCCESS",
FETCH_FAIL: "FETCH_FAIL",
};
const reducer = (state, action) => {
switch (action.type) {
case "FETCH_LOADING":
return { isLoading: true, isSuccess: false, isFail: false };
case "FETCH_SUCCESS":
return { isLoading: false, isSuccess: true, isFail: false };
case "FETCH_FAIL":
return { isLoading: false, isSuccess: false, isFail: true };
default:
return INIT_STATE;
}
};
function StateToReducer() {
const [state, dispatch] = useReducer(reducer, INIT_STATE);
const fetchData = () => {
dispatch({ type: ACTION_TYPE.FETCH_LOADING });
fetch(url)
.then(() => {
dispatch({ type: ACTION_TYPE.FETCH_SUCCESS });
})
.catch(() => {
dispatch({ type: ACTION_TYPE.FETCH_FAIL });
});
};
if (state.isLoading) return <LoadingComponent />;
if (state.isFail) return <ErrorComponent />;
if (state.isSuccess) return <SuccessComponent />;
}
useReducer를 언제 사용해야 할까?
- 상태 변경 로직이 매우 복잡할 때
- 여러 하위 값을 포함하는 상태를 관리할 때
- 다음 상태가 이전 상태에 강하게 의존적일 때
장점
- 상태 변경 로직의 중앙집중화
- 테스트하기 쉬운 코드 구조
- 복잡한 상태 관리 패턴 구현 용이
주의해야 할 점
- 과도한 사용은 오히려 복잡성을 높일 수 있음
- 간단한 상태 관리라면 useState 사용 추천
- 액션 타입과 페이로드를 일관되고 명확하게 관리
결론
useReducer는 React 애플리케이션의 상태 관리를 더욱 체계적이고 예측 가능하게 만들어주는 강력한 도구임.
- 복잡한 상태 로직을 다룰 때 useState보다 더 나은 선택이 될 수 있음.
- 상태 관리의 복잡성을 고려하여 적절히 사용한다면, 코드의 가독성과 유지보수성을 크게 향상시킬 수 있음.

