React 애플리케이션에서 데이터를 효율적으로 관리하기 위한 상태 관리 라이브러리야.
Zustand는 중앙 데이터 저장소
여러 컴포넌트가 같은 데이터를 필요로 할 때, 중앙에 데이터를 저장하고 필요할 때 꺼내 쓸 수 있도록 해줘. (예시)
로그인 여부: 헤더, 사이드바, 프로필 페이지 등에서 공유.
다크 모드 상태: 모든 페이지에서 같은 테마를 사용.
장바구니: 상품 상세 페이지에서 추가한 데이터를 장바구니 페이지에서도 보여줌.
1️⃣ Zustand 설치
| 패키지 매니저 | 설치 명령어 |
|---|---|
| Yarn | yarn add zustand |
| pnpm | pnpm add zustand |
2️⃣ Zustand 저장소 생성
import create from 'zustand';
// Zustand 저장소 생성
const useStore = create((set) => ({
isLoggedIn: false, // 초기 로그인 상태
login: () => set({ isLoggedIn: true }), // 로그인 상태 업데이트
logout: () => set({ isLoggedIn: false }), // 로그아웃 상태 업데이트
}));
3️⃣ Zustand 상태 사용
import React from 'react';
import { useStore } from './store';
const App = () => {
const isLoggedIn = useStore((state) => state.isLoggedIn);
const login = useStore((state) => state.login);
const logout = useStore((state) => state.logout);
return (
<div>
<h1>{isLoggedIn ? "Logged In" : "Logged Out"}</h1>
<button onClick={isLoggedIn ? logout : login}>
{isLoggedIn ? "Logout" : "Login"}
</button>
</div>
);
};
export default App;
1️⃣ 상태 관리 설정
Zustand로 다크 모드 상태를 중앙에서 관리
import create from 'zustand';
// Zustand 저장소 생성
const useStore = create((set) => ({
isDarkMode: false, // 다크 모드 상태
toggleDarkMode: () => set((state) => ({ isDarkMode: !state.isDarkMode })), // 상태 변경 함수
}));
2️⃣ 상태를 사용하는 컴포넌트
React 컴포넌트에서 다크 모드 상태를 가져와 UI를 변경
import React from 'react';
import { useStore } from './store';
const App = () => {
const isDarkMode = useStore((state) => state.isDarkMode); // 다크 모드 상태 가져오기
const toggleDarkMode = useStore((state) => state.toggleDarkMode); // 상태 변경 함수 가져오기
return (
<div style={{ backgroundColor: isDarkMode ? '#333' : '#fff', color: isDarkMode ? '#fff' : '#000', height: '100vh' }}>
<h1>{isDarkMode ? '다크 모드' : '라이트 모드'}</h1>
<button onClick={toggleDarkMode}>모드 전환</button>
</div>
);
};
export default App;
json-server는 JSON 파일 하나로 간단한 REST API 서버를 빠르게 만들고, 데이터를 읽고 쓰는 테스트를 할 수 있는 도구라고 생각하면 돼!