Zustand를 활용한 전역 상태
가볍고 강력하며 유연한 전역 상태 관리 솔루션을 위해 상태 관리 라이브러리인 Zustand를 통합합니다.
Zustand를 활용한 전역 상태은(는) CoddyKit의 무료 Next.js 15 Fullstack (App Router + Server Actions) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack (App Router + Server Actions) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Meet Zustand for Global State
Welcome to Zustand! It's a small, fast, and scalable state management solution for React and Next.js applications.
Unlike some other libraries, Zustand is known for its simplicity and minimal boilerplate, making it easy to learn and use.
- Simple: Uses a simple API based on React hooks.
- Fast: Optimized for performance, avoiding unnecessary re-renders.
- Scalable: Works well for small apps and large, complex projects.
Why Global State Matters
In larger applications, you often need to share data across many components that aren't directly connected (e.g., a user's login status or shopping cart items).
Without global state, you might find yourself 'prop drilling' – passing props down through many layers of components, which can be messy and hard to maintain.
Global state libraries like Zustand solve this by providing a central place to store and manage data accessible from any component.
Install Zustand in Your Project
Getting started with Zustand is straightforward. You just need to install it using your preferred package manager.
Open your terminal in your Next.js project directory and run one of the following commands:
- npm:
npm install zustand - yarn:
yarn add zustand - pnpm:
pnpm add zustand
Once installed, you're ready to create your first store!
Build Your First Zustand Store
A Zustand store is created using the create function. This function takes a callback that defines your initial state and any functions (actions) to modify that state.
The set argument in the callback is used to update the store's state. Let's define a basic counter store:
import { create } from 'zustand';
import React from 'react';
// Define your store
const useCounterStore = create((set) => ({
count: 0, // Initial state
}));
// A dummy component to make it runnable
function StoreDefined() {
return <p>Zustand store created!</p>;
}
export default function App() {
return <StoreDefined />;
}Access Store State in React
Now that we have a store, let's learn how to read its state within a React component. Zustand provides a hook (generated from your store) that you can call directly.
You can also use a 'selector' function to pick out just the specific pieces of state you need, avoiding unnecessary re-renders.
import { create } from 'zustand';
import React from 'react';
const useCounterStore = create((set) => ({
count: 0,
}));
// This component reads the 'count' from the store
function CountDisplay() {
const count = useCounterStore((state) => state.count);
return (
<div>
<h3>Current Count:</h3>
<p>{count}</p>
</div>
);
}
export default function App() {
return <CountDisplay />;
}Actions to Modify Store State
Stores are not just for reading data; they also define the actions that can modify the state. These actions are functions within your create call that use the set argument.
Let's add increment and decrement actions to our counter store and use them with buttons in a component:
import { create } from 'zustand';
import React from 'react';
const useCounterStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
function CounterApp() {
// Select both state and actions
const { count, increment, decrement } = useCounterStore();
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default function App() {
return <CounterApp />;
}Optimize with State Selectors
If your store holds many values, a component that only uses a small part of the state might still re-render when other, unrelated parts of the state change.
Zustand's selector pattern helps prevent this. By providing a selector function to useStore, your component will only re-render if the *selected* part of the state changes.
import { create } from 'zustand';
import React from 'react';
const useUserProfileStore = create((set) => ({
username: "Coddy",
email: "coddy@example.com",
loggedIn: true,
updateUsername: (name) => set({ username: name }),
}));
// This component only cares about the username
function UsernameDisplay() {
// Select only 'username' for efficient rendering
const username = useUserProfileStore((state) => state.username);
return (
<div>
<p>Hello, {username}!</p>
</div>
);
}
export default function App() {
return <UsernameDisplay />;
}Handle Asynchronous Updates
Zustand actions can easily handle asynchronous operations, such as fetching data from an API. You simply perform your async logic within the action and then call set when the data is ready.
This allows you to manage loading states or update data after network requests complete. Here's an example simulating a delayed update:
import { create } from 'zustand';
import React from 'react';
const useLoadingStore = create((set) => ({
isLoading: false,
message: "",
fetchData: async () => {
set({ isLoading: true, message: "Loading..." });
// Simulate an API call
await new Promise((resolve) => setTimeout(resolve, 1500));
set({ isLoading: false, message: "Data Loaded!" });
},
}));
function DataFetcher() {
const { isLoading, message, fetchData } = useLoadingStore();
return (
<div>
<p>{message}</p>
<button onClick={fetchData} disabled={isLoading}>
{isLoading ? "Fetching..." : "Fetch Data"}
</button>
</div>
);
}
export default function App() {
return <DataFetcher />;
}Structure Your Zustand Stores
For larger Next.js applications, it's good practice to organize your Zustand stores. Instead of defining all stores in one file, create a dedicated file for each store (e.g., stores/userStore.js, stores/cartStore.js).
This keeps your codebase clean, modular, and easier to navigate. You can then import and use these store hooks wherever needed.
Test Your Zustand Skills
Consider the following Zustand store definition:
import { create } from 'zustand';
const useSettingsStore = create((set) => ({
theme: 'light',
fontSize: 16,
toggleTheme: () => set((state) => ({
theme: state.theme === 'light' ? 'dark' : 'light',
})),
setFontSize: (size) => set({ fontSize: size }),
}));
If you call useSettingsStore((state) => state.theme) in a component, what will its initial value be?
Zustand: A Quick Review
Great job! You've successfully explored Zustand, a powerful and lightweight library for global state management in Next.js.
You learned how to:
- Create a simple Zustand store.
- Read state and dispatch actions in components.
- Optimize performance using selectors.
- Handle asynchronous updates.
Zustand's simplicity and flexibility make it an excellent choice for managing client-side global state in your applications. Keep practicing to master it!
자주 묻는 질문
“Zustand를 활용한 전역 상태” 강의는 무료인가요?
네 — “Zustand를 활용한 전역 상태” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack (App Router + Server Actions) 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack (App Router + Server Actions) 강의에는 총 4개의 강의가 포함되어 있습니다.
“Zustand를 활용한 전역 상태”에서 뭘 배우나요?
가볍고 강력하며 유연한 전역 상태 관리 솔루션을 위해 상태 관리 라이브러리인 Zustand를 통합합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack (App Router + Server Actions)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack (App Router + Server Actions)을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack (App Router + Server Actions)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Zustand를 활용한 전역 상태” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack (App Router + Server Actions) 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack (App Router + Server Actions) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- React Context API
- Zustand를 활용한 전역 상태
- 서버 상태 관리
- localStorage에 상태 저장