useReducer, useState의 대체함수, 이전 state에 의존적인 경우 useReducer를 써보씨오

김듑듑·2022년 7월 16일
0

프론트엔드

목록 보기
22/24

https://ko.reactjs.org/docs/hooks-reference.html

useReducer

  • useState의 대체함수
  • 다음 state가 이전 state에 의존적인 경우 useReducer를 써보씨오
  • redux랑 비슷비슷하긔
const [state, dispatch] = useReducer(리듀서, 초기arg, 초기값)

(state, action) => newState의 형태로 reducer를 받고
dispatch 메서드와 짝의 형태로 현재 state를 반환


카운터 예시를 보자
const [count, setCount] = useState(initialCount) 있고 count +1/-1/리셋 버튼이 있다.

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

0개의 댓글