코딩

React 상태 관리: 내부 상태, 외부 상태, 전역 상태 비교

CREAT8 2025. 2. 10.
728x90

React에서 상태 관리는 컴포넌트의 데이터 흐름을 관리하는 핵심 요소입니다. 이번 글에서는 React 내부 상태 관리, 외부 상태 관리, 전역 상태 관리의 차이점과 각각의 장점에 대해 살펴보겠습니다.

1. React 내부 상태 관리 (Local State)

내부 상태(Local State)는 개별 컴포넌트에서만 관리되는 상태입니다. useState 또는 useReducer를 활용할 수 있습니다.

✅ 장점

  • 간단한 구현: useState를 사용하면 쉽게 적용 가능
  • 컴포넌트 단위로 상태 분리: 유지보수성이 높아짐
  • 불필요한 리렌더링 최소화: 성능 최적화 가능

✅ 예제 코드


import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>현재 카운트: {count}</p>
      <button onClick={() => setCount(count + 1)}>증가</button>
    </div>
  );
}
    

2. React 외부 상태 관리 (External State)

외부 상태(External State)는 컴포넌트 외부에서 정의하여 여러 컴포넌트에서 공유할 수 있습니다. Context APIRedux 등을 활용할 수 있습니다.

✅ 장점

  • 컴포넌트 간 상태 공유 용이
  • Props Drilling 방지
  • 구조화된 상태 관리 가능

✅ 예제 코드 (Context API)


import React, { createContext, useState, useContext } from "react";

const CounterContext = createContext();

export function CounterProvider({ children }) {
  const [count, setCount] = useState(0);
  return (
    <CounterContext.Provider value={{ count, setCount }}>
      {children}
    </CounterContext.Provider>
  );
}

export function useCounter() {
  return useContext(CounterContext);
}
    

3. React 전역 상태 관리 (Global State)

전역 상태(Global State)는 애플리케이션 전체에서 접근 가능한 상태입니다. 대표적으로 Redux, Zustand, Recoil 등을 활용합니다.

✅ 장점

  • 대규모 애플리케이션에 적합
  • 다양한 상태 업데이트 방식 지원
  • 어디서든 접근 가능

✅ 예제 코드 (Redux 사용)


import { configureStore, createSlice } from "@reduxjs/toolkit";
import { Provider, useDispatch, useSelector } from "react-redux";

const counterSlice = createSlice({
  name: "counter",
  initialState: { value: 0 },
  reducers: {
    increment: (state) => {
      state.value += 1;
    },
  },
});

const store = configureStore({
  reducer: { counter: counterSlice.reducer },
});

function Counter() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();

  return (
    <div>
      <p>현재 카운트: {count}</p>
      <button onClick={() => dispatch(counterSlice.actions.increment())}>증가</button>
    </div>
  );
}

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}
    

4. 상태 관리 방식 비교

상태 관리 방식 장점 추천 사용 사례
내부 상태 구현이 간단하고 성능이 좋음 작은 규모의 컴포넌트 상태 관리
외부 상태 컴포넌트 간 상태 공유 가능 중간 규모 프로젝트
전역 상태 대규모 프로젝트에 적합 복잡한 상태 관리 필요

 

결론


React 상태 관리는 프로젝트의 규모와 복잡도에 따라 적절한 방식을 선택하는 것이 중요합니다.
작은 컴포넌트 내부에서만 상태를 관리할 경우 → useState를 사용한 내부 상태 관리
컴포넌트 간 상태 공유가 필요할 경우 → Context API 또는 useReducer 활용
전역에서 여러 곳에서 접근해야 하는 상태 → Redux, Zustand, Recoil 등 활용

프로젝트의 규모에 따라 적절한 상태 관리 방식을 선택하여 효율적인 React 애플리케이션을 구축해 보세요!

728x90

댓글

💲 추천 글