안녕하세요, 피터팬입니다!
오늘은 Reducer에 대해 알아볼 건데요
useRedcuer는, State(상태)를 관리하고 업데이트하는 Hook인 useState를 대체할 수 있는 Hook입니다.
useReducer를 사용하면 컴포넌트의 상태 업데이트 로직을 컴포넌트에서 분리시킬 수 있습니다.
적용법
import { useReducer } from "react";
사용법
1. reducer 선언
const reducer = (state,action){
switch(action.type){
case "INCREMENT":
return (~)
default:
return (~)
}
}
state ; reducer가 불리는 시점의 data
action ; 업데이트를 위한 정보를 가짐(type,value 등)
2. useReducer 선언
const [state,dispatch] = useReducer(reducer,initialState);
state ; 앞으로 컴포넌트에서 사용할 수 있는 state
dispatch ; action을 발생시키는 함수
3. dispatch를 통한 사용
dispatch 내의 객체(type,value 등)은 reducer의 action에 들어감
dispatch({type:"INCREMENT" , value:3})
예시
1. reducer 선언
const reducer = (state, action) => {
switch (action.type) {
case "USER_INPUT":
return { value: action.val, isValid: action.val.includes("@") };
case "INPUT_BLUR":
return { value: state.value, isValid: state.value.includes("@") };
default:
return { value: "", isValid: false };
}
};
2. useReducer 선언
const [emailState, dispatchEmail] = useReducer(emailReducer, {
value: "",
isValid: null,
});
3. dispatch함수 사용
const emailChangeHandler = (event) => {
dispatchEmail({ type: "USER_INPUT", val: event.target.value });
};
Reference
https://ko.reactjs.org/docs/hooks-reference.html
Hooks API Reference – React
A JavaScript library for building user interfaces
ko.reactjs.org
'WebProgramming > React' 카테고리의 다른 글
[React] Modal 작성하기 (0) | 2022.07.30 |
---|---|
[React] Component에서 Componet로 배열 전달하기 (0) | 2022.07.26 |
[React] useContext를 이용해 전역 props전달하기 2 (context.js로 분리시키기) (0) | 2022.07.22 |
[React] useEffect를 이용한 DOM조작 (0) | 2022.07.22 |
[React] useRef로 input 상태 관리하기 (0) | 2022.07.21 |
[React] Createportal을 이용해 특정 요소에 하위 요소 추가하기 (0) | 2022.07.21 |
[React] CSS Module을 이용한 컴포넌트 스타일링 (0) | 2022.07.20 |
[React] styled-component를 이용한 컴포넌트 스타일링 (0) | 2022.07.20 |