useState와 같이 상태를 관리하기 위해 사용한다.
복잡한 상태를 관리할 때 빛을 발한다.
reducer,action,dispatch로 이루어져있어서 redux와 비슷하게 쓰인다.
useReducer를 이용한 상태관리
import React, { useReducer, useState } from "react";
import styled from "styled-components";
const SaveButton = styled.button`
background-color: green;
font-weight: bold;
color: white;
border: none;
cursor: pointer;
padding: 20px;
margin: 20px;
`;
const TakeButton = styled.button`
background-color: red;
font-weight: bold;
color: white;
border: none;
cursor: pointer;
padding: 20px;
margin: 20px;
`;
const ACTION_TYPES = {
save: "save",
take: "take",
};
// 코드를 깔끔하게!
const reducer = (state, action) => {
// action을 토대로 state를 변경한다
console.log("you call reducer!");
switch (action.type) {
case ACTION_TYPES.save:
return state + action.payload;
case ACTION_TYPES.take:
return state - action.payload;
default:
return state;
}
};
// reducer 작성
const UseReducer = () => {
// useReducer : state 관리를 위한 react hook
// reducer,action,dispatch로 이루어져있다.
const [number, setNumber] = useState(0);
const [money, dispatch] = useReducer(reducer, 0); // (reducer,초기값)
// money => state
// dispatch => dispatch 함수
return (
<div>
<h1>useReducer</h1>
<h2>은행</h2>
<p>잔고 : {money}원</p>
<span>금액</span>
<input
type="number"
// value={number}
onChange={(e) => setNumber(parseInt(e.target.value))}
step="1000"
/>
<br />
<SaveButton
onClick={() => dispatch({ type: ACTION_TYPES.save, payload: number })}
>
예금하기
</SaveButton>
<TakeButton
onClick={() => dispatch({ type: ACTION_TYPES.take, payload: number })}
>
출금하기
</TakeButton>
</div>
);
};