const [state, dispatch] = useReducer(reducer, initialArg, init);
const initialState = {count: 0};
// state action 객체를 입력으로 받음
function reducer(state, action) {
//action에 따라 동작할 행동 선택 가능
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Counter() {
// useReducer는 reducer 함수, 초기 상태값, (지연생성시) 초기화 함수를 받음
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
/* dispatch 사용을 통해 reducer 함수 작동 */
<button onClick={() => dispatch({type: 'decrement'})}>-</button>
<button onClick={() => dispatch({type: 'increment'})}>+</button>
</>
);
}
const [state, dispatch] = useReducer(
reducer,
{count: initialCount}
);
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};
// init함수를 활용해 초기화 진행
case 'reset':
return init(action.payload);
default:
throw new Error();
}
}
function Counter({initialCount}) {
// 초기 state는 지연되서 생성되며, reducer 외부에서 초기 state 계산이 가능해짐
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.reactjs.org/docs/hooks-reference.html#usereducer