[데브코스/TIL] DAY52 - React Hook (useReducer)

Minha Ahn·2024년 12월 4일
0

데브코스

목록 보기
32/42
post-thumbnail

🖊️ useReducer

  • useState와 유사하며, 로컬 상태를 정의할 때 사용
  • const [상태, 액션발생함수] = useReducer(리듀서 함수, 초기값)
  • useState와의 차이점
    • useState: 상태를 변경하는 함수가 별도의 로직으로 여러 개 정의되어 상태 예측이 어려움. 간단함
    • useReducer: 상태를 변경하는 함수를 한 곳에 관리하므로 상태 예측이 가능함. 복잡함

사용 예시 - 1

// 리듀서 함수에서 사용되는 state와 action 타입 정의
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);
  
  // dispatch를 통해 액션 발생
  // reducer 함수를 직접 호출해도 작동하지 않음
  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)

profile
프론트엔드를 공부하고 있는 학생입니다🐌

2개의 댓글

comment-user-thumbnail
2024년 12월 9일

도움많이됐습니다

1개의 답글

관련 채용 정보