Zustand 저장소 만들기
Zustand를 설치하고 create로 저장소를 정의하며 상태 속성과 동작 함수를 추가하고, 저장소가 Redux 아키텍처와 어떻게 다른지 이해합니다.
Zustand 저장소 만들기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Is Zustand?
Zustand (German for 'state') is a minimal, fast state management library for React. Unlike Redux, it requires no boilerplate like action creators, reducers, or a Provider wrapper. You define a store as a single function, and any component can subscribe to it with a simple hook. It is ideal for apps that need global state without the complexity of Redux Toolkit.
Installing Zustand
Install Zustand from npm with a single command. It has zero dependencies and is compatible with React Native out of the box. The package is lightweight — under 1 kB gzipped — which keeps your app's bundle size small.
npm install zustandCreating Your First Store
Call create from Zustand and pass it a function that receives set and returns an object containing your state properties and actions. The returned value is a custom hook — conventionally named useXxxStore — that components call to access the store.
import { create } from 'zustand';
interface CounterStore {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
}
export const useCounterStore = create<CounterStore>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));The set Function
The set function is how Zustand updates state. You can pass it either a partial state object (Zustand merges it with existing state) or a callback that receives the current state and returns the updated portion. Zustand automatically notifies all subscribers when state changes.
// Partial object — Zustand merges it
set({ count: 0 });
// Callback — use when new value depends on previous value
set((state) => ({ count: state.count + 1 }));
// Replace entire state (pass true as second arg)
set(() => ({ count: 0, name: 'reset' }), true);No Provider Needed
One of Zustand's biggest advantages over Redux is that you do not need to wrap your component tree in a Provider. The store lives outside React and components subscribe to it directly via the returned hook. This means you can use the store anywhere — in components, in callbacks, or even outside React components.
// No Provider needed — just use the hook anywhere
function CounterDisplay() {
const count = useCounterStore((state) => state.count);
return <Text>Count: {count}</Text>;
}
function CounterButtons() {
const increment = useCounterStore((state) => state.increment);
const decrement = useCounterStore((state) => state.decrement);
return (
<View>
<Button title='+' onPress={increment} />
<Button title='-' onPress={decrement} />
</View>
);
}Subscribing to Specific State
Pass a selector function to the store hook to subscribe to only part of the state. The component re-renders only when the selected value changes. Without a selector, the component re-renders whenever any part of the store updates, which can hurt performance in large stores.
// Only re-renders when count changes
const count = useCounterStore((state) => state.count);
// Only re-renders when user.name changes
const username = useUserStore((state) => state.user.name);
// Without selector — re-renders on ANY store change (avoid this)
const everything = useCounterStore();Accessing the Store Outside React
Zustand stores expose a getState() method that reads the current state synchronously without hooks. There is also a subscribe() method for non-React subscriptions and a setState() method for imperative updates. This is useful in utility functions, API interceptors, or navigation helpers that run outside React component lifecycle.
// Access store state anywhere — no hooks required
import { useCounterStore } from './counterStore';
// Read state outside React
const currentCount = useCounterStore.getState().count;
// Update state outside React
useCounterStore.getState().increment();
// Subscribe outside React
const unsub = useCounterStore.subscribe((state) => {
console.log('Count changed to:', state.count);
});Async Actions in Zustand
Zustand actions can be async — just mark the function async and call set after the await. You do not need special async utilities like Redux's createAsyncThunk. You can add loading and error state directly to the store and update them inside the async action.
export const usePostsStore = create<PostsStore>((set) => ({
posts: [],
loading: false,
error: null,
fetchPosts: async () => {
set({ loading: true, error: null });
try {
const res = await fetch('https://api.example.com/posts');
const data = await res.json();
set({ posts: data, loading: false });
} catch (e) {
set({ error: 'Failed to load', loading: false });
}
},
}));Comparing Zustand and Redux
Redux Toolkit is more structured and provides stronger conventions for large teams, time-travel debugging, and complex state. Zustand excels when you need global state with minimal ceremony — a single file, no action types, no Provider. Both are valid choices; pick Zustand for small-to-medium apps or when you want to move fast without Redux boilerplate.
Organizing Multiple Stores
In larger apps, split your state into multiple focused stores rather than one massive store. For example, create useAuthStore, useCartStore, and useSettingsStore separately. Each store file is small, independently testable, and imported only by the components that need it. This prevents unrelated state changes from triggering unnecessary re-renders.
// stores/authStore.ts
export const useAuthStore = create<AuthStore>((set) => ({ /* ... */ }));
// stores/cartStore.ts
export const useCartStore = create<CartStore>((set) => ({ /* ... */ }));
// Component imports only what it needs
import { useAuthStore } from '../stores/authStore';
import { useCartStore } from '../stores/cartStore';Immer Middleware for Complex Updates
If your state is deeply nested and you want mutating-style updates (like Redux Toolkit's Immer integration), wrap the store creator with Zustand's immer middleware. With Immer, you can write state.user.preferences.theme = 'dark' instead of spreading every level of the object manually.
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
export const useSettingsStore = create(immer<SettingsStore>((set) => ({
user: { name: '', preferences: { theme: 'light', notifications: true } },
setTheme: (theme) => set((state) => {
state.user.preferences.theme = theme; // Immer makes this safe
}),
})));Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: Zustand creates global stores with minimal boilerplate using a single create call, no Provider is required because the store lives outside the React tree, and async actions work natively by marking store functions as async. Next up we explore reading and updating Zustand store state in components.
자주 묻는 질문
“Zustand 저장소 만들기” 강의는 무료인가요?
네 — “Zustand 저장소 만들기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“Zustand 저장소 만들기”에서 뭘 배우나요?
Zustand를 설치하고 create로 저장소를 정의하며 상태 속성과 동작 함수를 추가하고, 저장소가 Redux 아키텍처와 어떻게 다른지 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Zustand 저장소 만들기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.