useState 처럼 state를 생성하고 관리할 수 있게 해주는 도구이다.
여러개의 하위값을 포함하는 복잡한 state를 다뤄야할때 사용하면 코드를 깔끔하게 사용가능하고 유지보수가 편해진다.
Reducer Dispatch Action으로 이루어져있다.
거래내역 : state
은행 : Reducer -> state(거래내역)를 update 해주는 역할
사람: Dispatch -> 은행에 state(거래내역) 업데이트를 위한 요구
요구사항: Action -> 출금해주세요.
Dispatch -> Action -> Reducer -> State
state를 update를 하기 위해서는 dispatch라는 함수에 인자로 action을 넣어서 Reducer에 전달하여 components의 state를 action 안의 내용대로 update 시켜줌.
Dispatch(Action) -> Reducer(State,Action)
import React, { useState, useReducer } from 'react';
const ACTION_TYPES = {
deposit: 'deposit',
withdraw:'withdraw'
}
const reducer = (state, action) => {
console.log("action", state, action);
switch (action.type) {
case ACTION_TYPES.deposit:
return state + action.payload;
case ACTION_TYPES.withdraw:
return state - action.payload;
default:
return state;
}
};
function AppBank() {
const [number, setNumber] = useState(0);
// useReducer는 2가지 인자를 받음. useReducer(업데이트 역할, 초기State값)
const [money, dispatch] = useReducer(reducer, 0);
const handleNumber = (e) => {
setNumber(parseInt(e.target.value));
};
return (
<div className="App">
<h2>UseReducer 은행</h2>
<p>잔고: {money}원</p>
<input type="number" step="1000" value={number} onChange={handleNumber} />
<button
onClick={() => {
//action은 Object 형태로 보내고 Type을 넣어줌.
dispatch({ type: ACTION_TYPES.deposit, payload: number });
}}
>
예금
</button>
<button onClick={() => {
dispatch({ type: ACTION_TYPES.withdraw, payload: number });
}}>출금</button>
</div>
);
}
export default AppBank;