https://ko.reactjs.org/docs/hooks-reference.html
const [state, dispatch] = useReducer(리듀서, 초기arg, 초기값)
(state, action) => newState의 형태로 reducer를 받고
dispatch 메서드와 짝의 형태로 현재 state를 반환
카운터 예시를 보자
const [count, setCount] = useState(initialCount)
있고 count +1/-1/리셋
버튼이 있다.
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>
</>
);
}