useReducer 구조와 원리
useReducer는 리액트에서 상태 관리를 위해 사용하는 또 다른 훅이다. 이 훅은 상태와 디스패치 함수를 반환하며, 상태를 업데이트하기 위해 액션을 디스패치하는 방식으로 작동. 이 구조는 복잡한 상태 로직을 관리할 때 유용하다.
const [state, dispatch] = useReducer(reducer, initialArg, init);
📌 인자 목록 | 인자 | 설명 | | ———– | ————————————————————————————– | | reducer | (state, action) => newState
형태의 함수. 액션에 따라 상태를 어떻게 변경할지 정의함. | | initialArg | 초기 상태값. 숫자, 객체, 배열 등 다양하게 가능. | | init (선택) | initialArg
를 초기화하는 함수. 초기 계산이 복잡할 때 유용한 Lazy Initialization 방식. |
참고: init이 있을 경우 initialArg는 init의 인자로 들어가며, init(initialArg)의 반환값이 초기 state가 된다.
🔄 reducer 함수 구조 예제
const reducer = (state, action) => {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
};
🚀 dispatch 와 action 속성 ✅ 기본 구조
dispatch({ type: "INCREMENT" });
✅ action 객체 속성 | 속성 | 설명 | | type | 반드시 있어야 하는 문자열. 어떤 작업을 수행할지 나타냄. | | payload | (선택) 상태 업데이트에 필요한 추가 데이터. | | meta | (선택) 디버깅, 로깅, 미들웨어 처리 등에 쓰이는 부가 정보. |
예시
dispatch({
type: "SAVE_DATA",
payload: { userId: 123, value: "Hello" },
meta: { timestamp: Date.now() },
});
🧪 전체 예제 통합
const init = (initialCount) => ({ count: initialCount });
const reducer = (state, action) => {
switch (action.type) {
case "reset":
return init(action.payload);
case "increment":
return { count: state.count + 1 };
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, 5, init);