🖊️ useReducer
- useState와 유사하며, 로컬 상태를 정의할 때 사용
const [상태, 액션발생함수] = useReducer(리듀서 함수, 초기값)
- useState와의 차이점
- useState: 상태를 변경하는 함수가 별도의 로직으로 여러 개 정의되어 상태 예측이 어려움. 간단함
- useReducer: 상태를 변경하는 함수를 한 곳에 관리하므로 상태 예측이 가능함. 복잡함
사용 예시 - 1
type ReducerState = number;
type ReducerAction = string;
function reducer(state: ReducerState, action: ReducerAction) {
switch (action) {
case "decrement":
return state - 1;
case "reset":
return 0;
case "increment":
return state + 1;
default:
return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, 0);
return (
<>
<h1>Count: {state}</h1>
<button onClick={() => dispatch("decrement")}>감소</button>
<button onClick={() => dispatch("reset")}>리셋</button>
<button onClick={() => dispatch("increment")}>증가</button>
</>
)
사용 예시 - 2
interface ReducerState {
email: string;
password: string;
agree: boolean;
error: string;
}
type ReducerAction =
| {
type: "SET_EMAIL";
payload: string;
}
| {
type: "SET_PASSWORD";
payload: string;
}
| {
type: "SET_AGREE";
payload: boolean;
}
| {
type: "SET_ERROR";
payload: string;
};
function reducer(state: ReducerState, action: ReducerAction) {
switch (action.type) {
case "SET_EMAIL":
return { ...state, mail: action.payload };
case "SET_PASSWORD":
return { ...state, password: action.payload };
case "SET_AGREE":
return { ...state, agree: action.payload };
case "SET_ERROR":
return { ...state, error: action.payload };
default:
return state;
}
}
const initialState: ReducerState = {
email: "",
password: "",
agree: false,
error: "",
};
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
const validationForm = () => {
if (!state.email) {
dispatch({ type: "SET_ERROR", payload: "이메일을 입력해주세요." });
return false;
}
};
return(
<form>
<input
type="text"
placeholder="someone@example.com"
name="mail"
value={state.email}
onChange={(e) => {
dispatch({ type: "SET_EMAIL", payload: e.target.value });
}}
/>
</form>
)
📌 출처
수코딩(https://www.sucoding.kr)
도움많이됐습니다