나의 주니어 개발 일기/REACT
[REACT] useReducer
추억을 백앤드하자
2025. 7. 3. 13:24
728x90
반응형
SMALL
useReducer
지금까지의 state를 useReducer로도 만들 수 있다.
다만 상태 관리 코드를 컴포넌트 외부로 분리해서 관리할 수 있다는 것이 큰 차이점 이다.
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가 호출되면, useReducer(reducer)인수로 있는 reducer 함수가 호출된다.
dispatch({
type: "Increase",
data: 1,
});
};
const onClickMinus = () => {
//인수: 상태가 어떻게 변화되길 원하는지(액션객체)
//dispatch가 호출되면, useReducer(reducer)인수로 있는 reducer 함수가 호출된다.
dispatch({
type: "Decrease",
data: 1,
});
};
return(
<div>
<h1>{state}</h1>
<button onClick={onClickPlus}>+</button>
<button onClick={onClickMinus}>-</button>
</div>);
}
export default Exam;
App.jsx
import Exam from './components/Exam'
function App() {
return (
<div className='App'>
<Exam />
</div>
);
}
export default App
728x90
반응형
LIST