위처럼, useState 를 사용하여 count state 를 1 , 10, 100, 1000 을 더하도록 상태관리를 할 수 있다.
이렇게 component 안에서 useState를 통해 state 관리를 하다 보면 코드가 길어지고 복잡해 질 수 있다. 더욱이 하나의 component 에서 state 가 여러개 존재할 수 있고, 객체로 복잡한 state 를 가지게 되면 하나의 component 가 무거워 질 수 있다. 그러므로 useState 를 사용한 상태 관리는 되도록 지양 하고 useReducer를 사용하여 component 상태 변화 로직을 분리하여야 한다.
useReducer 를 사용해 보자
const reducer = {state, action} => {
switch(action.type)
case 1:
return state + 1;
case 10:
return state + 10;
case 100:
return state + 100;
case 100:
return state + 1000;
default:
return state;
}
const Counter = () => {
const [count, dispatch] = useReducer(reducer, 1);
return (
<div>
{count}
<button onClick={() => dispatch({ type : 1 })}> add 1 </button>
<button onClick={() => dispatch({ type : 10 })}> add 10 </button>
<button onClick={() => dispatch({ type : 100 })}> add 100 </button>
<button onClick={() => dispatch({ type : 1000 })}> add 1000 </button>
</div>
}
}