복잡한 state 관리에 유용.
const [state, dispatch] = useReducer(reducer, initialState);
state: 현재 상태를 나타내는 값입니다.
dispatch: 액션을 발생시켜 상태를 업데이트하는 함수입니다,
reducer: 상태 업데이트를 처리하는 리듀서 함수입니다.
initialState: 초기 상태로 사용될 값 입니다
import React, {useReducer} from "react"
const [emailState, dispatchEmail] = useReducer(리듀서 함수, {
//초기값
value: "",
isValid: null,
});
리듀서 함수에 사용되는 데이터는 컴포넌트 내부에서 이 함수로 전달 되기 때문에 컴포넌트 안에 만들지 않아도 됩니다.
const reducer = (state,action)=>{
return {value:"",isValid:false}
}
const reducer = (state,action)=>{
if(action.type =="USER_EMAIL"){
return {value:action.value,isValid:action.value.includes("@")}
}
return {value:"",isValid:false}
}
4.이벤트 핸들러에 디스페치
const emailChangeHandler = (event) => {
dispatchEmail({ type: "USER_EMAIL", val: event.target.value });
};
dispatch → 리듀서 함수 action → state 상태 업데이트