안녕하세요 36기 YB 정희연입니다!
React를 쓰다 보면 상태(state)를 관리해야 하는 순간이 자주 찾아옵니다.
useState, useReducer만으로는 충분하지 않다는 걸 느끼기 시작하면, 전역 상태 관리에 관심을 가지게 되는 것 같아요!
로그인 정보, 테마, 언어 설정, 장바구니 등 여러 컴포넌트에서 공유되는 상태가 바로 그 예입니다.
이때 가장 먼저 접하게 되는 게 Context API, 그리고 이후에는 Recoil, Zustand, Jotai 같은 외부 라이브러리입니다.
이번 주차에서는 각각의 개념, 장단점, 그리고 사용법을 쉽게 예제를 통해 비교해볼게요!

💡 Context API란?
Context API는 React에서 컴포넌트 간에 데이터를 쉽게 공유할 수 있도록 도와주는 기능입니다.
props drilling(컴포넌트 여러 단계를 거쳐 props 전달하는 것)을 피할 수 있어요.
✅ 언제 쓰면 좋을까?
- 간단한 전역 상태가 있을 때 (예: 테마, 언어, 로그인 여부)
- 외부 라이브러리를 도입하고 싶지 않을 때
💭 기본 예제
// 1. Context 만들기
import React, { createContext, useContext, useState } from "react";
const ThemeContext = createContext();
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState("light");
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
// 2. Context 사용하기
const ThemeToggler = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
현재 테마: {theme}
</button>
);
};
😕 그런데 단점은?
- 컴포넌트가 많아질수록 Provider 중첩이 많아짐
- 상태가 바뀌면 하위 컴포넌트 전체가 리렌더링 됨
- 상태별로 여러 Context를 만들어야 하니 관리가 복잡해짐
➡️ 그래서 이런 단점을 보완하고자 등장한 것이 RLTNF 상태 관리 라이브러리들입니다!
💡 Recoil: Facebook이 만든 반응형 상태 관리
Recoil은 atom(상태) 과 selector(파생 상태) 개념을 가진 라이브러리입니다!
Context보다 더 세밀하게 컴포넌트를 리렌더링할 수 있어요.
📦 설치
npm install recoil
💭 기본 예제
// recoil/counterAtom.js
import { atom } from "recoil";
export const counterState = atom({
key: "counterState",
default: 0,
});
// App.tsx
import { RecoilRoot, useRecoilState } from "recoil";
import { counterState } from "./recoil/counterAtom";
function Counter() {
const [count, setCount] = useRecoilState(counterState);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
export default function App() {
return (
<RecoilRoot>
<Counter />
</RecoilRoot>
);
}
☺️ 장점
- atom 단위로 상태가 나뉘어 있어 리렌더링이 최적화
- 파생 상태 (selector), 비동기 상태 지원
- React 방식과 잘 어울림
💡 Zustand: 간결하고 빠른 상태 관리
📦 설치
npm install zustand
💭 기본 예제
// store/counterStore.js
import { create } from "zustand";
export const useCounterStore = create((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
}));
// App.tsx
import { useCounterStore } from "./store/counterStore";
function Counter() {
const { count, increase } = useCounterStore();
return <button onClick={increase}>Zustand Count: {count}</button>;
}
☺️ 장점
- API가 매우 직관적
- Context 없이 상태 공유 가능
- React 외부에서도 사용 가능
💡 Jotai: 작지만 강력한 원자(atom) 기반 상태 관리
Jotai는 Recoil처럼 atom을 사용하는데 더 간단합니다!
필요할 때만 상태를 만들고, 필요한 곳에서만 쓰는 방식입니다.
📦 설치
npm install jotai
💭 기본 예제
// store/counterAtom.js
import { atom } from "jotai";
export const counterAtom = atom(0);
// App.tsx
import { useAtom } from "jotai";
import { counterAtom } from "./store/counterAtom";
function Counter() {
const [count, setCount] = useAtom(counterAtom);
return <button onClick={() => setCount(count + 1)}>Jotai Count: {count}</button>;
}
☺️ 장점
- 매우 간단한 API
- Recoil보다 가볍고 설정이 쉬움
- 작은 프로젝트에 적합
🧭 무엇을 언제 써야 할까?
상황 | 추천도구 |
테마, 언어 설정, 로그인 여부 등 간단한 전역 상태 | Context API |
상태가 많고, 성능 최적화가 필요할 때 | Recoil or Zustand |
아주 간단하면서도 가볍게 쓰고 싶을 때 | Jotai |
Redux 스타일 + 가벼움이 필요할 때 | Zustand |
📚 참고 자료
Recoil
A state management library for React.
recoiljs.org
Jotai, primitive and flexible state management for React
Jotai takes a bottom-up approach to global React state management with an atomic model inspired by Recoil. One can build state by combining atoms and renders are optimized based on atom dependency. This solves the extra re-render issue of React context and
jotai.org
https://ui.toast.com/posts/ko_20210812
React 상태 관리 라이브러리 Zustand의 코드를 파헤쳐보자
TOAST UI Calendar의 새로운 상태 관리 방법을 도입하기 위해 참고한 라이브러리 Zustand의 코드를 분석해본다.
ui.toast.com
React에서의, 전역 상태관리는 왜 필요할까?
전역 상태 관리의 필요성에 대해 이야기해보겠습니다. React는 컴포넌트 기반의 라이브러리로, 각 컴포넌트는 자신의 상태를 가집니다. 하지만 애플리케이션이 커질수록 상태 관리가 복잡해지기
velog.io
'2주차' 카테고리의 다른 글
메모리 누수와 성능 관리 (0) | 2025.04.25 |
---|---|
리액트 렌더링 과정 (0) | 2025.04.25 |
반응형 프로그래밍이 무엇일까요? (1) | 2025.04.25 |
Vanilla JS와 React (Vanilla JS는 언제 쓰는건가?) (0) | 2025.04.25 |
JavaScript 이벤트 전파 (0) | 2025.04.24 |