[React hooks] useReducer

Inhye Jeong·2020년 9월 1일
0

React

목록 보기
4/5

1. Reducer란?

reducer란 무엇인가요?

Re(act State Pro)ducer => Reducer

reducer의 정의 정리

다시말해, 리듀서라고 불리는 이유는 리듀서가 reduce()함수에서 사용하는 콜백함수이기때문에 리듀서라고 불립니다.

2. useReducer

  • (state, action) => newState의 형태로 reducer를 받고 dispatch 메서드와 짝의 형태로 현재 state를 반환합니다.
const [state, dispatch] = useReducer(reducer, initialArg, init);
  • example
const initialState = {count: 0};

// (state, action) => newState 형태의 reducer를 정의한다.
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);
  // dispatch로 action의 type을 보내 state를 업데이트한다.
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
profile
Frontend Engineer in @KakaoStyle

0개의 댓글