useReducer는 언제 쓸까?
React에서 상태를 관리할 때 useState를 쓴다.
import React, { useState } from 'react';
function Counter() {
const [number, setNumber] = useState(0);
const onIncrease = () => {
setNumber(prevNumber => prevNumber + 1);
};
const onDecrease = () => {
setNumber(prevNumber => prevNumber - 1);
};
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default Counter;
여기서 counter를 살펴보면
H1에 state에 있는 number를 표기해주고
숫자 1을 늘리고 줄일 수 있는 버튼이 있다.
여기서 onIncrease함수와 onDecrease함수를 사용해서
숫자의 state값을 변경해주고 있는데, 상태 업데이트를 다양하게 하거나 이전에 있는 값을 그대로 가져와
변화를 줄 경우에 counter 컴포넌트에 작성해야 하는 양이 늘어나게 되고 가독성도 떨어진다.
그리고 비슷한 동작을 하는 다른 컴포넌트가 있을 경우에도 재사용하기가 어렵다.
이를 해결하기 위해 useReducer라는 리액트 훅을 사용하면 좋다.
import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
function Counter() {
const [number, dispatch] = useReducer(reducer, 0);
const onIncrease = () => {
dispatch({ type: 'INCREMENT' });
};
const onDecrease = () => {
dispatch({ type: 'DECREMENT' });
};
return (
<div>
<h1>{number}</h1>
<button onClick={onIncrease}>+1</button>
<button onClick={onDecrease}>-1</button>
</div>
);
}
export default Counter;
위 코드는 reducer를 사용한 화면이다
reducer는 사용하고 싶은 곳에 useReducer를 넣어주면 된다.
useReducer의 매개변수를 살펴보면 실제 reducer동작을 하는 함수가 첫 번째 인자이고, 두번째 인자는 초기값이다.
reducer함수는 useReducer에 선언된 prev값(코드에서 첫 번째 인자인 state)를 받고 action인자를 전달받는다.
함수를 사용할 때는 dispatch와 함께 reducer함수에서 선언한 type 중 사용할 함수를 object형식으로 할당해주면 된다.
reducer는 state성질을 가지고 있으므로 setState를 해주지 않아도 useReducer로 선언한 변수의 state가 변화되어
리액트에서도 render가 일어난다.
리액트에서 유용한 state와 함께 거기서 한 발 더 나아간 Reducer까지 두 가지 모두 적재적소에 사용하면
큰 도움이 될 것 같다.