복잡하고 많은 상태 업데이트 로직을 가지고 있는 컴포넌트에서 코드가 길어지고 복잡해지는 것이 좋지 않기 때문에
복잡하고 긴 상태변화 로직을 컴포넌트 밖으로 분리하는 기능이다. useState처럼 React의 상태관리를 돕는 Hooks 중 하나이다. useReducer를 이용하면 상태변화 로직들을 컴포넌트에서 분리하여 컴포넌트를 더 가볍게 작성할 수 있게 도와준다.
상태변화 로직을 많이 갖고있는 useState로 작성된 컴포넌트이다.
const Counter = () => {
const [count, setCount] = useState(1);
const add1 = () => {
setCount(count + 1);
};
const add10 = () => {
setCount(count + 10);
};
const add100 = () => {
setCount(count + 100);
};
const add1000 = () => {
setCount(count + 1000);
};
const add10000 = () => {
setCount(count + 10000);
};
return (
<div>
{count}
<button onClick={add1}>add 1</button>
<button onClick={add10}>add 10</button>
<button onClick={add100}>add 100</button>
<button onClick={add1000}>add 1000</button>
<button onClick={add10000}>add 10000</button>
</div>
);
};
useReducer
는 useState처럼 사용할 수 있다.
📌 기본 공식 : const [state, dispatch] = useReducer(reducer, 1);
→ state
: 상태
→ dispatch
: 상태를 변화시키는 action을 발생시키는 함수
→ reducer
: useReducer의 첫번째 인자, dispatch가 일으킨 상태 변화를 처리해주는 함수
→ 1
: useReducer의 두번째 인자, state의 초기값으로 설정(1은 임시로 써둔 값임)
useReducer
를 사용하여state
를 만들면 초기값이 1이 할당되고, 그 값의 상태를 변화시키고 싶으면
상태변화 함수인dispatch
를 호출한다. dispatch가 상태변화를 일으키면 상태변화 처리 함수인reducer
가 처리한다.
const reducer = (state, action) => {
switch (action.type) {
case 1:
return state + 1;
case 10:
return state + 10;
case 100:
return state + 100;
case 1000:
return state + 1000;
case 10000:
return state + 10000;
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>
<button onClick={() => dispatch( {type:10000} )}> add 10000 </button>
</div>
);
};
상태변화 함수 dispatch
가 호출되면 dispatch는 객체를 전달한다. 이 객체는 type
이라는 프로퍼티를 포함하고 있다.
이때, dispatch와 함께 전달되는 객체를 action
(= 상태변화를 설명할) 객체라고 한다.
dispatch가 호출되면서 전달된 action 객체는 reducer
함수로 넘어가게 된다.
위의 코드에서 버튼 add 1을 눌렀다고 가정하면, reducer
함수의 인자 state는 1, action 은 dispatch가 넘겨준 type:1 을 받게 된다.
그리고 reducer
의 case들이 return하는 값들이 state가 된다.
첫번째 case 1에서는 action.type을 1로 받았기 때문에 return하는 새로운 상태가 2가 된다.