web

[ 모던 리액트 : Deep Dive ] - 03장 리액트 훅 깊게 살펴보기 useReducer

햇옥수수 2023. 12. 22. 05:24

🚀 useReducer

✅ useReducer란?

- useReducer는 useState의 심화 버전으로 볼 수 있다. 

- 복잡하고 수정해야하는 경우의 수가 많은 state일 경우, 여러개의 state를 묶어 useReducer로 관리하는 것이 효율적이다. 

- state 값이 변경되는 시나리오를 제한적으로 두어 변경을 빠르게 확인하고자 하는 목적성을 지닌다. 즉, dispatcher로만 state를 수정할 수 있게 해서, state 접근은 컴포넌트에서만 가능하게 하는 것이다. 

 

✅ 사용방법

import { useReducer } from 'react';

function reducer(state, action) {
  if (action.type === 'changed_name') {
    return {
      name: state.name + '꽃다리',
    };
  } else if (action.type === 'deleted_name') {
    return {
      name: '',
    };
  }
  throw Error('Unknown action.');
}

export default function Counter() {
  const [state, dispatcher] = useReducer(reducer, { name: '수수' });

  function handleChangeName() {
    dispatcher({ type: 'changed_name' });
  }

  function handleDeleteName() {
    dispatcher({ type: 'deleted_name' });
  }

  return (
    <>
      <button onClick={handleChangeName}>change name</button>
      <button onClick={handleDeleteName}>delete name</button>
      <p>Hello! You are {state.name}.</p>
    </>
  );
}

 

✔️ dispatcher는 state를 업데이트하는 함수이다. 값이 아니라, state를 변경할 수 있는 action을 넘겨준다. 

 

🩵 useReducer와 useState는 공통적으로 클로저를 활용해 state를 관리하기 때문에 필요에 따라 두 훅 중 원하는 것을 사용하면 된다.