const [state, dispatch] = useReducer(reducer, initialState, init);
(state, action) => newState)
형태의 함수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();
}
}
초기 상태를 지연 초기화하기 위한 함수
initialState를 인자로 받아 실제 초기 상태를 반환
function init(initialCount) {
return {count: initialCount};
}
const [state, dispatch] = useReducer(reducer, initialCount, init);
액션 발생시키는 함수
액션 객체 인자로 받음
→ 해당 객체는 reducer 함수에 전달
dispatch({type: 'INCREMENT'})
dispatch({type: 'DECREMENT'})
useState
보다 더 적합const initialState = {count: 0};
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();
}
} // 컴포넌트 외부에 state 업데이트 로직 존재
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'DECREMENT'})}>-</button>
<button onClick={() => dispatch({type: 'INCREMENT'})}>+</button>
</>
);
}
useState | useReducer | |
---|---|---|
state 개수 | 1개 | 1개 이상 |
state 자료형 | 원시타입 | 복잡한 구조 |
~일 경우 추천한다!
useState
보다 더 많은 보일러플레이트 코드 필요→ state 가 단순할 경우엔 useState
사용
useReducer에 대해 깔끔하게 정리해주셨네요!
useState와 비교해서 언제 사용하는 게 더 적합한지 잘 설명해주신 것 같습니다! useReducer의 단점에 대해 잘 모르고 있었는데 오버엔지니어링이 될 수도 있겠네요 배워갑니다 :)