useState 보다 복잡한 상태의 로직을 관리import { useReducer } from 'react';
function reducer(state, action) {
// ...
}
function MyComponent() {
const [state, dispatch] = useReducer(reducer, initalState);
// ...
reducer 함수state 와 action을 파라미터로 받음state의 초기값dispatch 함수function reducer(state, action){
switch (action.type) {
case 'increment':
return {age: state.age + 1}
case 'decrement':
return {age: state.age - 1}
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, {age: 20})
return (
<div>
<p>Age: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div>
)
}
useReducer 를 호출dispatch 함수에서 사용자의 action 을 파라미터로 받아reducer 함수를 통해 상태를 변화시킴state는
read-only이므로 state를 직접 변화시키지 않고 reducer 함수에서새로운 객체를 반환해야 한다.
❌ 잘못된 예
function reducer(state, action) {
switch (action.type) {
case 'increment': {
// 🚩 Don't mutate an object in state like this:
state.age = state.age + 1;
return state;
}
⭕️ 올바른 예
function reducer(state, action) {
switch (action.type) {
case 'increment': {
return {
// ✅ return a new object
age: state.age + 1
};
}
reducer 함수 안에 은닉 ✅ 참고자료
useState의 경쟁자 useReducer - Youtube
useReducer vs. useState
React 공식문서