본문 바로가기
Front-end/React

전역 상태 관리 필수 개념과 React에서 최적 솔루션

by mooyou 2025. 2. 6.
728x90
300x250
SMALL

전역 상태 관리 라이브러리 비교

React에서는 상태(state)를 관리하는 다양한 방법이 있다. 프로젝트 규모나 복잡도에 따라 적절한 방법을 선택하는 것이 중요하다.

전역 상태 관리 라이브러리가 필요한 이유

  • 여러 컴포넌트에서 같은 데이터를 공유해야 할 때
  • props를 계속 전달하는 Props Drilling 문제 해결
  • 상태 변경이 많아 관리가 복잡할 때

1. Context API(기본 제공)

특징

  • React에서 기본 제공하는 전역 상태 관리 기능
  • createContext()와 useContext()를 활용하여 간단하게 사용 가능
  • 간단한 상태 관리에는 충분하지만, 상태 업데이트가 잦으면 성능 문제 발생 가능

언제 사용할까?

  • 소규모 프로젝트
  • 상태 변경이 자주일어나지 않는 경우
const ThemeContext = createContext();

const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState("light");
  return <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>;
};

const ThemedComponent = () => {
  const { theme, setTheme } = useContext(ThemeContext);
  return (
    <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
      현재 테마: {theme}
    </button>
  );
};

 


 

2. Redux(가장 유명한 라이브러리)

특징

  • 가장 널리 사용되는 상태 관리 라이브러리
  • store라는 중앙 저장소에서 상태를 관리
  • dispatch를 통해 상태 변경(불변성 유지)

언제 사용할까?

  • 대규모 애플리케이션
  • 복잡한 상태 관리가 필요한 경우
import { configureStore, createSlice } from "@reduxjs/toolkit";
import { Provider, useDispatch, useSelector } from "react-redux";

// Slice 생성
const themeSlice = createSlice({
  name: "theme",
  initialState: { value: "light" },
  reducers: {
    toggleTheme: (state) => {
      state.value = state.value === "light" ? "dark" : "light";
    },
  },
});

// Store 설정
const store = configureStore({ reducer: { theme: themeSlice.reducer } });

// 컴포넌트
const ThemedComponent = () => {
  const theme = useSelector((state) => state.theme.value);
  const dispatch = useDispatch();

  return (
    <button onClick={() => dispatch(themeSlice.actions.toggleTheme())}>
      현재 테마: {theme}
    </button>
  );
};

// 최상위 컴포넌트 감싸기
const App = () => (
  <Provider store={store}>
    <ThemedComponent />
  </Provider>
);

 


3. Recoil (React 친화적 상태 관리)

특징

  • Facebook에서 개발한 React상태 관리 라이브러리
  • atom(전역 상태 단위)과 selector(계산된 상태)를 사용
  • useRecoilState()를 이용해 상태를 쉽게 관리 가능

언제 사용할까?

  • React 프로젝트에서 자연스럽게 상태 관리를 하고 싶을 때
  • 비동기 데이터를 쉽게 다루고 싶을 때
import { atom, useRecoilState, RecoilRoot } from "recoil";

// Atom 생성
const themeState = atom({
  key: "themeState",
  default: "light",
});

const ThemedComponent = () => {
  const [theme, setTheme] = useRecoilState(themeState);
  return (
    <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
      현재 테마: {theme}
    </button>
  );
};

const App = () => (
  <RecoilRoot>
    <ThemedComponent />
  </RecoilRoot>
);

 


4. Zustand (가벼운 상태 관리)

특징

  • Redux보다 가볍고 간단한 상태 관리 라이브러리
  • useStore() 훅을 이용해 상태를 간편하게 관리
  • Context API보다 성능이 뛰어나면서도 사용법이 간단

연제 사용할까?

  • 간결한 상태 관리가 필요할 때
  • Redux는 너무 무겁고, Context API는 부족할 때
import create from "zustand";

// Zustand 스토어 생성
const useStore = create((set) => ({
  theme: "light",
  toggleTheme: () => set((state) => ({ theme: state.theme === "light" ? "dark" : "light" })),
}));

const ThemedComponent = () => {
  const { theme, toggleTheme } = useStore();
  return <button onClick={toggleTheme}>현재 테마: {theme}</button>;
};

const App = () => <ThemedComponent />;

 


 

어떤 라이브러리를 선택할까?

라이브러리 장점 단점 추천 상황
Context API 기본 제공, 간단함 상태가 많아지면 성능 저하 소규모 프로젝트
Redux 강력한 상태 관리, 개발 도구 지원 설정이 복잡, 코드량 많음 대규모 프로젝트
Recoil React 친화적, 비동기 관리 용이 성숙도가 낮음(개발된지 오래되지 않음) 중/대형 프로젝트
Zustand 가볍고 간단함 공식 문서 부족 중소규모 프로젝트

 

728x90
반응형
LIST

댓글