useReducer은 뭘까?
useState와 거의 비슷하다고 볼 수 있다..
사실 더 정교하게 상태를 제어할 수 있는 Hook 입니다.
모든 `useState` 는 `useReducer`로 대체가 가능합니다!
특히 상태가 복잡해질수록 `useReducer`가 더 깔끔하고 유지보수에 좋습니다~~.
왜 `useReducer`를 써야할까?
`useState`를 사용한다면, 컴포넌트 내부에 상태 관리 코드를 작성해야한다는 점이 있었죠, 그렇게 되면 코드가 섞이게 됩니다.
(App에 작성하면 ,, 너무 복잡혀요)
function App() {
const [todos, setTodos] = useState(mockData);
const idRef = useRef(3);
const onCreate = (content) => {
const newTodo = {
id: idRef.current++,
isDone: false,
content: content,
date: new Date().getTime(),
};
setTodos([newTodo, ...todos]);
};
근런데 `useReducer`를 사용하면?
상태 관리 로직을 컴포넌트 외부에 별도의 함수로 상태 관리 코드를 분리할 수 있어, 코드가 더 깔끔해지는 장점이 있다.
function reducer(state, action) {
// 상태 변경 로직 분리!
}
function App() {
const [todos, dispatch] = useReducer(reducer) ;
//...
}
useReducer 사용하는 방법
- `import { useReducer } from "react";`
- `const [state, dispatch] = useReducer(reducer, 초기값);`
- 상태를 바꾸고 싶을 땐 `dispatch({ type : "TYPE", data : 값 });`
import { useReducer } from "react";
function reducer(state, action) {
if (action.type === "INCREASE") {
return state + action.data;
}
}
//////
const Exam = () => {
const [state, dispatch] = useReducer(reducer, 0);
const onClickPlus = () => {
dispatch({
type: "INCREASE",
data: 1,
});
};
};
정리,,,
- `dispatch`: 상태를 바꾸고 싶을 때 호출하는 액션 발사기
- dispatch에는 인수로 : 상태가 어떻게 변화되길 원하는지를 넣는다, 이걸 액션 객체라고 한다.
- `action`: `dispatch` 로 보낸 객체
- ` { type : "INCREASE", data: 1 }
- `reducer`: `state`와 `action` 을 받아서 새로운 state를 반환하는 함수
만일 이런 type들이 많아지면 if문 말고 `switch` 문으로 작성하는게 편하긴 하다
'프레임워크 및 라이브러리 > React' 카테고리의 다른 글
[React] Context 복습하기 (0) | 2025.04.10 |
---|---|
[React] useRef 복습하기! (0) | 2025.04.10 |
[React] useEffect (0) | 2025.04.09 |
[React] Life Cycle 라이프 사이클 (0) | 2025.04.09 |
[React] useState hook 복습하기 (0) | 2025.04.08 |