useReducer

const [state, dispatch] = useReducer(reducer, initialArg, init);

useState의 대체 함수, (state, action) ⇒ newState 의 형태로 reducer를 받고 dispatch 메서드와 짝의 형태로 현재 state를 반환한다.

이 hook 함수를 사용하면 컴포넌트의 상태 업테이트 로직을 분리시킬 수 있다.

function reducer(state, action) {
  // 새로운 상태를 만드는 로직
  // const nextState = ...
  return nextState;
}

action 은 업데이트를 위한 정보를 가지고 있다. 주로 type 값을 지닌 객체의 형태로 많이 사용되지만 정해진 규칙은 아니다.

const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>);
}

여기서는 initialState = {count : 0} 이라고 설정하여 초기값을 0으로 설정하였다.

다른 방식으로도 설정 할 수 있다. ⬇

const initialState = {
  inputs: {
    username: '',
    email: ''
  },
  users: [
    {
      id: 1,
      username: 'velopert',
      email: '[email protected]',
      active: true
    },
    {
      id: 2,
      username: 'tester',
      email: '[email protected]',
      active: false
    },
    {
      id: 3,
      username: 'liz',
      email: '[email protected]',
      active: false
    }
  ]
};

언제 useReducer 를 사용해야 할까? rather than useState