슬라이스 패턴과 Devtools 통합
슬라이스 패턴을 사용해 큰 저장소를 논리적인 슬라이스로 구성하고, 개발 중 시간 이동 디버깅을 위해 Zustand DevTools 미들웨어를 추가합니다.
슬라이스 패턴과 Devtools 통합은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Organize Stores with Slices?
As a Zustand store grows, keeping all state and actions in a single object becomes hard to maintain. The slices pattern splits the store into multiple focused sections, each defined as a separate function. All slices are combined into one store, so components still access everything through a single hook. This mirrors the Redux Toolkit slice concept but in Zustand's minimal style.
Defining a Slice Function
A Zustand slice is a function that accepts set, get, and optionally the whole store initializer, and returns an object containing state and actions for that domain. Define each slice in its own file and import them into the combined store. The slice function signature mirrors the main store creator exactly.
// slices/counterSlice.ts
import type { StateCreator } from 'zustand';
import type { AppStore } from '../useAppStore';
export interface CounterSlice {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
}
export const createCounterSlice: StateCreator<AppStore, [], [], CounterSlice> =
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
});Combining Slices into One Store
Import all your slice creator functions and merge them inside a single create call using the spread operator. The combined store type is the intersection of all slice interfaces. Components can then access any slice's state and actions through the same useAppStore hook.
// useAppStore.ts
import { create } from 'zustand';
import { createCounterSlice, CounterSlice } from './slices/counterSlice';
import { createUserSlice, UserSlice } from './slices/userSlice';
export type AppStore = CounterSlice & UserSlice;
export const useAppStore = create<AppStore>((set, get, api) => ({
...createCounterSlice(set, get, api),
...createUserSlice(set, get, api),
}));Cross-Slice Communication
Slices can call each other's actions or read each other's state using the get function. This is how one slice can react to another slice's changes without tight coupling. For example, a cart slice can read the user slice's auth token and include it in an API request when checking out.
export const createCartSlice: StateCreator<AppStore, [], [], CartSlice> =
(set, get) => ({
items: [],
checkout: async () => {
const token = get().user.token; // read from userSlice
await api.checkout(get().items, token);
set({ items: [] });
},
});What Is the Zustand DevTools Middleware?
The devtools middleware connects your Zustand store to the Redux DevTools browser extension. Once connected, you can inspect every state snapshot, view the action name that triggered each change, and time-travel back to any previous state. It is invaluable for debugging complex state sequences during development.
Adding DevTools Middleware
Wrap your store creator with the devtools middleware imported from zustand/middleware. Pass an optional configuration object with a name property to label the store in the DevTools panel. Only enable DevTools in development to avoid performance overhead in production builds.
import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
export const useCounterStore = create(
devtools(
(set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}),
{ name: 'CounterStore' }
)
);Labeling Actions in DevTools
By default, DevTools labels every state change with anonymous. Pass a descriptive string as the third argument to set to give each action a meaningful name in the DevTools timeline. This makes it much easier to trace which user interaction triggered each state change.
increment: () =>
set(
(state) => ({ count: state.count + 1 }),
false, // false = merge (not replace)
'counter/increment' // action label in DevTools
),
reset: () =>
set({ count: 0 }, false, 'counter/reset'),Combining DevTools with persist
When using both persist and devtools, wrap the store in both middlewares. The order matters: devtools should be the outermost wrapper so it can observe all state changes, including those from rehydration. Nest persist inside devtools to see rehydration actions in the DevTools timeline.
import { create } from 'zustand';
import { persist, devtools, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const useSettingsStore = create(
devtools(
persist(
(set) => ({ theme: 'light', setTheme: (t) => set({ theme: t }) }),
{ name: 'settings', storage: createJSONStorage(() => AsyncStorage) }
),
{ name: 'SettingsStore' }
)
);Slices with persist and DevTools
In large apps, combine all three patterns: slices for organization, persist for storage, and devtools for debugging. Wrap the merged slice object with persist and devtools. Define the combined type as the intersection of all slice interfaces so TypeScript correctly types the full store.
export const useAppStore = create<AppStore>()(
devtools(
persist(
(set, get, api) => ({
...createCounterSlice(set, get, api),
...createUserSlice(set, get, api),
}),
{ name: 'app-store', storage: createJSONStorage(() => AsyncStorage) }
),
{ name: 'AppStore' }
)
);Naming Conventions for Slices
Use consistent naming to make large stores easy to navigate. Name slice files after the domain (e.g., authSlice.ts, cartSlice.ts), prefix action names with the domain in DevTools labels (e.g., auth/login, cart/addItem), and keep each slice under 100 lines. Split further if a slice starts handling unrelated concerns.
When Not to Use Slices
The slices pattern adds complexity. If your store has fewer than five state fields and two or three actions, keep it as a single create call — the overhead of splitting is not worth it. Reserve slices for stores that have grown to the point where a single file is difficult to understand or when multiple developers work on different features that share the same store.
Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: the slices pattern splits a large Zustand store into focused domain functions that are merged in one create call, the devtools middleware connects the store to Redux DevTools for state inspection and time-travel, and labeling set calls with action name strings makes the DevTools timeline meaningful. Next up we explore reading and writing with AsyncStorage directly.
자주 묻는 질문
“슬라이스 패턴과 Devtools 통합” 강의는 무료인가요?
네 — “슬라이스 패턴과 Devtools 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“슬라이스 패턴과 Devtools 통합”에서 뭘 배우나요?
슬라이스 패턴을 사용해 큰 저장소를 논리적인 슬라이스로 구성하고, 개발 중 시간 이동 디버깅을 위해 Zustand DevTools 미들웨어를 추가합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
React Native Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“슬라이스 패턴과 Devtools 통합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Zustand 저장소 만들기
- 컴포넌트에서 저장소 상태 읽고 업데이트하기
- AsyncStorage로 Zustand 상태 유지하기
- 슬라이스 패턴과 Devtools 통합