티스토리 뷰

반응형

🚀 FastAPI 기반 로컬 LLM + RAG 챗봇 – React Query와 Zustand의 차이점 및 활용법

이번 글에서는 Next.js에서 Zustand와 React Query를 비교하고, 각 라이브러리를 어떻게 활용하면 좋은지를 다룹니다.
Zustand와 React Query의 차이점을 이해하고, 함께 사용하는 방법을 학습합니다.
Next.js의 서버 상태와 클라이언트 상태를 효율적으로 관리하는 전략을 정리합니다.


📌 1. Zustand vs React Query 비교

Zustand와 React Query는 Next.js에서 상태를 관리하는 방식이 다릅니다.
각각의 용도를 정확히 이해하면, 최적의 상태 관리 전략을 수립할 수 있습니다.

✅ 1.1 주요 차이점 비교

기능 Zustand React Query

상태 유형 클라이언트 상태 (UI 중심) 서버 상태 (API 데이터)
사용 목적 다크 모드, 모달 상태, 사용자 입력 값 데이터베이스에서 가져온 데이터 (API)
데이터 캐싱 ❌ 없음 ✅ API 데이터 자동 캐싱
서버 연동 ❌ 직접 요청 필요 (fetch) ✅ 자동 요청 및 데이터 동기화
데이터 갱신 setState로 직접 업데이트 invalidateQueries로 갱신 가능
렌더링 최적화 ✅ 불필요한 리렌더링 방지 ✅ 자동 리렌더링 최적화

정리:

  • Zustand는 클라이언트 UI 상태를 관리할 때 적합합니다.
  • React Query는 서버 데이터를 관리하고 캐싱할 때 강력한 도구입니다.
  • 두 개를 함께 사용하면 클라이언트 상태와 서버 상태를 효과적으로 분리할 수 있습니다. 🚀

📌 2. Zustand와 React Query의 올바른 사용법

반응형

✅ 2.1 Zustand를 사용해야 하는 경우

  • 다크 모드 (darkMode 상태)
  • 모달 창 열림 여부 (isModalOpen)
  • 장바구니 상태 (cartItems)
  • 로컬에서 변경되는 UI 관련 상태

📌 예제 – Zustand를 활용한 다크 모드 전환 (app/store/useThemeStore.ts)

import { create } from "zustand";

interface ThemeState {
  darkMode: boolean;
  toggleDarkMode: () => void;
}

const useThemeStore = create<ThemeState>((set) => ({
  darkMode: false,
  toggleDarkMode: () => set((state) => ({ darkMode: !state.darkMode })),
}));

export default useThemeStore;

📌 app/components/ThemeToggle.tsx (Zustand 활용)

"use client";

import useThemeStore from "../store/useThemeStore";

export default function ThemeToggle() {
  const { darkMode, toggleDarkMode } = useThemeStore();

  return (
    <button
      className={`p-2 rounded ${darkMode ? "bg-black text-white" : "bg-white text-black"}`}
      onClick={toggleDarkMode}
    >
      {darkMode ? "🌙 다크 모드" : "☀️ 라이트 모드"}
    </button>
  );
}

Zustand는 컴포넌트의 UI 상태를 빠르고 간결하게 관리하는 데 유용합니다! 🚀


✅ 2.2 React Query를 사용해야 하는 경우

  • 서버 API 데이터를 가져올 때 (fetch API, REST API, GraphQL)
  • 데이터 캐싱이 필요할 때
  • 데이터를 주기적으로 업데이트해야 할 때
  • 검색 결과, 상품 목록 등 비동기 데이터 관리

📌 예제 – React Query를 활용한 상품 목록 (app/products/page.tsx)

"use client";

import { useQuery } from "@tanstack/react-query";

const fetchProducts = async () => {
  const res = await fetch("https://fakestoreapi.com/products");
  return res.json();
};

export default function Products() {
  const { data: products, isLoading, error } = useQuery({
    queryKey: ["products"],
    queryFn: fetchProducts,
  });

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>오류 발생!</p>;

  return (
    <div>
      <h1>상품 목록</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>{product.title}</li>
        ))}
      </ul>
    </div>
  );
}

React Query는 서버에서 데이터를 가져오고 캐싱하는 데 강력한 도구입니다! 🚀


📌 3. Zustand + React Query 함께 사용하기

✅ 3.1 사용자 정보 (React Query) + 로그인 상태 (Zustand) 관리

Zustand와 React Query를 함께 사용하면 로그인 상태와 사용자 정보를 효율적으로 관리할 수 있습니다.

📌 app/store/useAuthStore.ts (Zustand로 로그인 상태 관리)

import { create } from "zustand";

interface AuthState {
  isAuthenticated: boolean;
  setAuth: (auth: boolean) => void;
}

const useAuthStore = create<AuthState>((set) => ({
  isAuthenticated: false,
  setAuth: (auth) => set({ isAuthenticated: auth }),
}));

export default useAuthStore;

📌 app/components/UserProfile.tsx (React Query로 사용자 정보 요청)

"use client";

import { useQuery } from "@tanstack/react-query";
import useAuthStore from "../store/useAuthStore";

const fetchUserProfile = async () => {
  const res = await fetch("/api/user");
  return res.json();
};

export default function UserProfile() {
  const { isAuthenticated } = useAuthStore();
  const { data: user, isLoading } = useQuery({
    queryKey: ["user"],
    queryFn: fetchUserProfile,
    enabled: isAuthenticated, // 로그인 상태일 때만 실행
  });

  if (!isAuthenticated) return <p>로그인이 필요합니다.</p>;
  if (isLoading) return <p>Loading...</p>;

  return <p>환영합니다, {user.name}님!</p>;
}

Zustand로 로그인 상태를 관리하고, React Query로 사용자 데이터를 불러올 수 있습니다! 🚀


📌 4. 최적의 상태 관리 전략 선택하기

패칭 방식 사용 예시 특징

Zustand 다크 모드, 로그인 상태, UI 상태 빠르고 간편한 상태 관리
React Query 서버 API 데이터 (상품 목록, 사용자 정보) 캐싱 및 자동 데이터 갱신
Zustand + React Query 로그인 상태(Zustand) + 사용자 데이터(React Query) 상태 분리를 통한 최적의 성능

Next.js에서 Zustand와 React Query를 함께 사용하면 상태를 더욱 효과적으로 관리할 수 있습니다! 🚀


📌 5. 결론 및 다음 단계

Zustand와 React Query의 차이점을 이해했습니다.
Zustand는 클라이언트 UI 상태 관리에 적합하고, React Query는 서버 데이터 관리에 최적화되어 있음을 확인했습니다.
Zustand와 React Query를 함께 사용하는 전략을 실습했습니다.

🚀 다음 글에서는 "4.1 Next.js 보안 및 인증"을 진행합니다!

 

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함
반응형