useReducer는 리액트에서 상태 관리를 할 때 사용하는 훅이다.
useState와 비슷하지만, 상태가 복잡하거나 여러 값이 함께 바뀔 때 더 유용하다.
컴포넌트가 다루는 상태가 여러 개이고, 상태 변경 로직이 복잡할 때는 useState로 관리하기 어렵다.
이럴 때 useReducer를 사용하면 상태 변경을 명확한 규칙에 따라 처리할 수 있어 관리가 편해진다.
jsx
복사편집
import React, { useReducer } from 'react';
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:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<><p>현재 카운트: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</>
);
}
reducer는 현재 상태와 액션을 받아서 새로운 상태를 반환하는 함수이다.
dispatch는 상태 변경을 요청하는 함수이며, 액션 객체를 인자로 받는다.
이렇게 하면 상태 변경 로직이 분리되어 코드가 더 깔끔해지고 관리하기 쉬워진다.