useState의 대체함수로 사용한다.
(state, action) => newState의 형태로 reducer를 받고 dispatch 메서드와 짝의 형태로 state 를 반환한다.
다수의 하윗값을 포함하는 복잡한 정적 로직을 만드는 경우나 다음 state가 이전 state에 의존적인 경우에 보통 useState보다 useReducer를 선호한다.
useReducer 는 state 및 dispatch 메서드를 반환한다.
(1) state : 컴포넌트에서 사용할 state(상태)
(2) dispatch : reducer 함수를 실행시키며, 컴포넌트 내에서 state의 업데이트를 구현
(3) reducer : 컴포넌트 외부에서 state를 업데이트하는 로직을 담당하는 함수
(4) state와 action 매개변수를 이용해서 기존의 state를 대체할 새로운 state를 반환
(5) initialState : 초기 state값 지정
(6) init : 초기 함수
아래는 useReducer를 사용하여 카운터를 작성한 예시이다.
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();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
지연 초기화 : 초기화 시점을 그 값이 처음 필요할 때까지 늦추는 기법
useReducer는 다음과 같이 지연 초기화 사용시 세번째 인자로 초기화 하는 함수를 사용한다.
const [state, dispatch] = useReducer(reducer, initialArg, init?)
function init(initialCount) {
return {count: initialCount};
}
function reducer(state, action) {
//새로운 상태를 만드는 로직
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}
function Counter({initialCount}) {
const [state, dispatch] = useReducer(reducer, initialCount, init);
return (
<>
Count: {state.count}
<button
onClick={() => dispatch({type: 'reset', payload: initialCount})}>
Reset
</button>
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
참조 :
https://ko.legacy.reactjs.org/
https://ossam5.tistory.com/429