React Hook - useReducer

YEONGHUN KO·2022년 2월 19일
1

REACT JS - BASIC

목록 보기
13/30
post-thumbnail

useReducer는 higher-order function 의 reduce랑 같은 개념을 공유하고 있다. reducer 함수를 pass하면 reduce함수에 의해서 state가 새로 갱신되어 최종값이 저장된다. 그래서 useState를 대체할 수 있다.바로 코드로 살펴보자

우선 숫자를 올리는 버튼과 내리는 버튼을 만들어보자. reducer에 의해 선별적으로 state를 manipulate할 수 있는 것이 useReducer의 특징이다. useReducer는 reducer와 initialVal을 인자로 받는다.

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

useReducer는 state와 dispatch를 리턴한다. dispatch에 들어간 인자는 reducer의 두번째 para로 뽑아서 쓸 수 있고, 리턴을 하게 되면 리턴값이 그대로 state에 저장된다. 보통 switch statement로 state를 선별적으로 다루게 된다.

profile
'과연 이게 최선일까?' 끊임없이 생각하기

0개의 댓글