9.1) useReducer를 소개합니다
useReducer
- 컴포넌트 내부에 새로운 State를 생성하는 React Hook
- 모든 useState는 useReducer로 대체 가능
- 상태 관리 코드를 컴포넌트 외부로 분리할 수 있음
= useState는 컴포넌트 내부에 상태 관리 코드를 작성해야함
- 컴포넌트의 메인 역할은 UI를 렌더링하는 것으로, 상태 관리 코드가 많아지는 것은 주객이 전도되는 것
const [state, dispatch] = useReducer({reducer}, {initData})
dispatch({action})
fuction reducer(state, action)
Exam.jsx
import { useReducer } from "react";
function reducer(state, action) {
console.log(state, action);
switch (action.type) {
case "INCREASE":
return state + action.data;
case "DECREASE":
return state - action.data;
default:
return state;
}
}
const Exam = () => {
const [state, dispatch] = useReducer(reducer, 0);
const onClickPlus = () => {
dispatch({
type: "INCREASE",
data: 1,
});
};
const onClickMinus = () => {
dispatch({
type: "DECREASE",
data: 1,
});
};
return (
<div>
<h1>{state}</h1>
<button onClick={onClickPlus}>+</button>
<button onClick={onClickMinus}>-</button>
</div>
);
};
export default Exam;