รูปแบบ Slices และการผสานรวม Devtools
จัดระเบียบ store ขนาดใหญ่เป็น slice เชิงตรรกะด้วยรูปแบบ slice และเพิ่มมิดเดิลแวร์ Zustand DevTools เพื่อดีบักแบบย้อนเวลาในระหว่างการพัฒนา
รูปแบบ Slices และการผสานรวม Devtools เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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.
คำถามที่พบบ่อย
บทเรียน “รูปแบบ Slices และการผสานรวม Devtools” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “รูปแบบ Slices และการผสานรวม Devtools” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบ Slices และการผสานรวม Devtools”
จัดระเบียบ store ขนาดใหญ่เป็น slice เชิงตรรกะด้วยรูปแบบ slice และเพิ่มมิดเดิลแวร์ Zustand DevTools เพื่อดีบักแบบย้อนเวลาในระหว่างการพัฒนา คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “รูปแบบ Slices และการผสานรวม Devtools” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้าง Zustand Store
- การอ่านและอัปเดตสถานะ Store ในคอมโพเนนต์
- การคงสถานะ Zustand ด้วย AsyncStorage
- รูปแบบ Slices และการผสานรวม Devtools