import { useReducer } from 'react';
const [state, dispatch] = useReducer(reducer, 초기값);reducer 함수: 현재 상태와 액션을 받아 새로운 상태를 반환하는 함수이다.
액션: type과 payload를 포함한 객체이다.
type Action = {
type: 'plus' | 'minus';
payload?: number;
};
const reducer = (count: number, { type, payload }: Action) => {
switch (type) {
case 'plus':
return count + (payload ?? 1);
case 'minus':
return count - 1;
default:
return count;
}
};
dispatch({ type: 'plus', payload: value });
// context 파일
type Action = { type: string; payload?: number };
const reducer = (count: number, { type, payload = 1 }: Action) => {
switch (type) {
case 'plus':
return count + payload;
case 'minus':
return count - payload;
default:
return count;
}
};
const CounterContextProvider = ({ children }: PropsWithChildren) => {
const [count, dispatch] = useReducer(reducer, 0);
const plusCount = () => dispatch({ type: 'plus', payload: 2 });
const minusCount = () => dispatch({ type: 'minus' });
return (
<CounterContext.Provider value={{ count, plusCount, minusCount }}>
{children}
</CounterContext.Provider>
);
};
// 다른 파일
const { count, minusCount } = useCounter();
useStateuseReducer // useState
const [count, setCount] = useState(0);
setCount(count + 1); // 단순히 현재 상태에 1을 더하는 예제
// useReducer
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
// ...
}
};
const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'INCREMENT' }); // 복잡한 로직을 처리하는 예제