728x90
컴포넌트 외부에 State 관리 로직 분리✅
- 로직
useState()와 거의 동일
import { useReducer, useState } from "react"
function Reducer(state, action) { // Reducer 함수
if(action.type === "DECREASE"){
return state - action.data;
}
else if(action.type === "INCREASE"){
return state + action.data;
}
}
export default function B() {
// count는 State값, dispatch는 type과 data와 같은 action값
const [count, dispatch] = useReducer(Reducer, 0);
return (<div>
<div>
<h4>{count}</h4>
<div>
<button onClick={() => {
dispatch({
type: "INCREASE",
data: 1
})
}}>+</button>
<button onClick={() => {
dispatch({
type: "DECREASE",
data: 1
});
}}>-</button>
</div>
</div>
</div>)
}
-> count를 통해 State값을 전달받고, Dispatch()를 통해 type과 data와 같은 action값을 전달
-> Reducer()로 값들을 받아와 로직 실행
'Front-End Study > React.js' 카테고리의 다른 글
페이지 라우팅 (0) | 2024.02.22 |
---|---|
최적화 (0) | 2024.02.21 |
React Custom Hooks (0) | 2024.02.20 |
리액트의 라이프 사이클 (1) | 2024.02.17 |
State로 사용자 입력 관리하기, Ref로 요소 지정하기 (0) | 2024.02.15 |