useReducer

iamsummer__·2021년 6월 23일
0
const [state, dispatch] = useReducer(reducer, initialArg, init);

useState의 대체함수입니다.
(state, action) => newState형태로 reducer를 받고,
dispatch와 state를 반환합니다.

복잡한 정적 로직이나, 이전 state에 의존적인 경우에 주로 사용합니다.
dispatch를 통해 업데이트를 트리거하여 컴포넌트의 성능을 최적화합니다.

또한 dispatch함수는 리렌더링시에도 변경되지 않아, useEffect, useCallback를 사용하지 않아도 됩니다.

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>
    </>
  );
}

초기화 지연

세번째 인자에 init함수를 전달하면 초기 state를 조금 지연해서 생성할 수 있습니다.

function init(initialCount) {
  return {count: initialCount};
}

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

const [state, dispatch] = useReducer(reducer, initialCount, init);
profile
개발하는 프론트엔드개발자

0개의 댓글