useReducer

jaehan·2022년 5월 10일
0

React

목록 보기
3/33
post-thumbnail

💻 useReducer

useState로도 상태 업데이트를 해줄 수 있지만 useState로 관리하기 복잡하고 귀찮을때 사용 하기 좋은 것 같다.

💡 reducer

현재 상태와 액션 객체를 파라미터로 받아와서 새로운 상태를 반환 해주는 함수

function reducer(state, action) {
  // 새로운 상태를 만드는 로직
  // const nextState = ...
  return nextState;
}

✔️ action은 업데이트를 위한 정보를 가진다.(type 값을 가진 객체값)

{
  type: 'INCREMENT'
}
{
  type: 'DECREMENT'
}

👇 useReducer 사용법

const [state, dispatch] = useReducer(reducer, initialState);

✔️ dispatch -> 액션을 방생시키는 함수 ex) dispatch({type:'INCREMENT})
✔️ state -> 컴포넌트에서 사용 할 수 있는 상태

사용 예

import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}

function Counter() {
  const [number, dispatch] = useReducer(reducer, 0);

  const onIncrease = () => {
    dispatch({ type: 'INCREMENT' });
  };

  const onDecrease = () => {
    dispatch({ type: 'DECREMENT' });
  };

  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
}

export default Counter;
  1. reducer를 먼저 생성 해준다
    (switch문으로 dispatch의 type에 따라 나눠서 return 값을 설정해준다)
  2. useReducer로 state와 dispatch 설정해준다.
  3. 값을 업데이트 해주고 싶을때 dispatch({ type: ... })의 형태로 사용한다.

0개의 댓글