React useReducer

gusdas·2022년 4월 24일
0

용어 정리

목록 보기
28/28

사용이유

useState의 대체 함수로 컴포넌트 상태관리하는 값이 많고 복잡하다면 useReducer를 사용하여 읽히기 쉽게 바꿔준다.

사용법

const initialState = {count: 0};

function reducer(state, action) { //reducer 함수 작성
  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); 
  const onDecrease = () => {
  dispatch({type: 'decrement'})
  };
  
 const onIncrement = () => {
  dispatch({type: 'increment'})
  };
  return (
    <>
      Count: {state.count}
      <button onClick={onDecrease}>-</button>
      <button onClick={onIncrement}>+</button>
    </>
  );
}

const [state, dispatch] = useReducer(reducer, initialState);
state: 상태
dispatch: 함수
useReducer(리듀서함수, state의 초기값)

profile
웹개발자가 되자

0개의 댓글