[React] useReducer를 이용한 state 관리

TD·2023년 9월 14일

React 스터디

목록 보기
2/4
post-thumbnail

useReducer

💁‍♀️ 언제 사용할까?

  1. useState 보다 복잡한 상태의 로직을 관리
  2. 이전 상태값과 이후 상태값이 상단한 관계가 있을 때

🧩 구성요소

import { useReducer } from 'react';

function reducer(state, action) {
  // ...
}

function MyComponent() {
  const [state, dispatch] = useReducer(reducer, initalState);
  // ...

📍 useReducer의 파라미터

  1. reducer 함수
    • state가 어떻게 변화할지 정의하는 함수
    • stateaction을 파라미터로 받음
  2. state의 초기값

📍 useReducer의 리턴값

  1. 현재 state
  2. dispatch 함수

🧩 사용법

function reducer(state, action){
	switch (action.type) {
      case 'increment':
        return {age: state.age + 1}
      case 'decrement':
        return {age: state.age - 1}
      default:
      	throw new Error();
    }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, {age: 20})

  return (
    <div>
      <p>Age: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  )
}
  1. 컴포넌트에서 useReducer 를 호출
  2. dispatch 함수에서 사용자의 action 을 파라미터로 받아
  3. reducer 함수를 통해 상태를 변화시킴

🚨 주의: state는 read-only

state는 read-only 이므로 state를 직접 변화시키지 않고 reducer 함수에서 새로운 객체를 반환해야 한다.

❌ 잘못된 예

function reducer(state, action) {
  switch (action.type) {
    case 'increment': {
      // 🚩 Don't mutate an object in state like this:
      state.age = state.age + 1;
      return state;
    }

⭕️ 올바른 예

function reducer(state, action) {
  switch (action.type) {
    case 'increment': {
      return {
        // ✅ return a new object
        age: state.age + 1
      };
    }

👍 장점

  1. state를 사용하는 쪽에선 복잡한 로직을 처리하지 않아도 된다.
  2. 상태를 변경시키는 과정을 reducer 함수 안에 은닉 ✅ 

참고자료
useState의 경쟁자 useReducer - Youtube
useReducer vs. useState
React 공식문서

profile
주저하지 않고 탐구하는 프론트엔드 개발자를 목표로 합니다.

0개의 댓글