Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | import { useReducer } from 'react';
export default function useCounter(init, step) {
// 카운터를 관리하기 위한 State/Reducer를 준비한다.
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case 'update':
return { count: state.count + action.step };
case 'reset' :
return { count: action.init };
default:
return state;
}
},
{
count: init
}
);
// 각 버튼에 대응하는 핸들러
const handleUp = () => dispatch({ type: 'update', step });
const handleDown = () => dispatch({ type: 'update', step: -step });
const handleReset = () => dispatch({ type: 'reset', init });
return [state, handleUp, handleDown, handleReset];
}
// Code 7-8-4
// import { useDebugValue } from 'react';
// import { useReducer } from 'react';
// export default function useCounter(init, step) {
// // 카운터를 관리하기 위한 State/Reducer를 준비한다.
// const [state, dispatch] = useReducer(
// (state, action) => {
// switch (action.type) {
// case 'update':
// return { count: state.count + action.step };
// case 'reset' :
// return { count: action.init };
// default:
// return state;
// }
// },
// {
// count: init
// }
// );
// useDebugValue(state.count >= 10 ? '10 Over' : '10 Less');
// // 각 버튼에 대응하는 핸들러
// const handleUp = () => dispatch({ type: 'update', step });
// const handleDown = () => dispatch({ type: 'update', step: -step });
// const handleReset = () => dispatch({ type: 'reset', init });
// return [state, handleUp, handleDown, handleReset];
// } |