Skip to content
useState기술 정리

Switching from useState to useReducer for user input

1 min readTech notesMoved from my Tistory blogRead the Korean original

The previous login setup
Figure 1. The previous login setup
ts
type UserInfoState = {
  id: string;
  passWord: string;
};

type UserInfoAction =
  | {
      type: "setId";
      payload: string;
    }
  | {
      type: "setPassWord";
      payload: string;
    };

I used to manage the information entered at login or sign-up with the useState hook, and I want to write about the useReducer approach I learned at work.

First, you need to create a reducer function.

Also, since I'm using TypeScript, the types of state and action have to be declared.

ts
function reducer(state: UserInfoState, action: UserInfoAction) {
  switch (action.type) {
    case "setId":
      return {
        ...state,
        id: action.payload,
      };
    case "setPassWord":
      return {
        ...state,
        passWord: action.payload,
      };
    default:
      return state;
  }
}

Once the types are declared, everything is ready.

jsx
function App() {
  const [userInfo, dispatch] = useReducer(reducer, { id: "", passWord: "" });
  return (
    <>
      아이디 :{" "}
      <input
        type="text"
        onChange={(e) => dispatch({ type: "setId", payload: e.target.value })}
      />
      <br />
      비밀번호 :
      <input
        type="password"
        onChange={(e) =>
          dispatch({ type: "setPassWord", payload: e.target.value })
        }
      />
      <br />
      <button onClick={() => console.log(userInfo)}>로그인</button>
    </>
  );
}

Pass the reducer function and the initial state to the useReducer hook.

Then, when an onChange event fires on the id input, the dispatch function uses the type I defined to update that state value with the payload.

The difference between the old state approach and useReducer seems huge to me. Unlike the states I used to manage one by one, I can manage the user information all at once, so it feels much simpler.

Managing user information with useReducer
Figure 2. Managing user information with useReducer
  • #useReducer
  • #useState
  • #user info

More in Tech notes