SKILL.md--- name: rn-zustand-patterns description: Zustand state management patterns for React Native. Use when working with Zustand stores, debugging state timing issues, or implementing async actions in Zustand. --- # Zustand Patterns for React Native ## Problem Statement Zustand's simplicity hides important timing details. `set()` is synchronous, but React re-renders are batched. `getState()` escapes stale closures. Async actions in stores need careful handling. Understanding these internals prevents subtle bugs. --- ## Pattern: set() is Synchronous, Renders are Batched **Problem:** Assuming state is "ready" for React immediately after `set()`. ```typescript const useStore = create((set, get) => ({ count: 0, increment: () => { set({ count: get().count + 1 }); // State IS updated here (set is sync) console.log(get().count); // ✅ Shows new value // But React hasn't re-rendered yet // Component will see old value until next render cycle }, })); ``` **Key insight:** - `set()` updates the store synchronously - `getState()` immediately reflects the new value - React components re-render asynchronously (batched) **When this matters:** - Chaining multiple state updates - Validating state after update - Debugging "stale" component values --- ## Pattern: getState() Escapes Stale Closures **Problem:** Callbacks and async functions capture state at creation time. Using `get()` or `getState()` always gets current state. ```typescript const useStore = create((set, get) => ({ answers: {}, // WRONG - state captured at function creation saveAnswerBad: (questionId: string, value: number) => { setTimeout(() => { const answers = get().answers; // ❌ This is fine // But if someone passed `answers` as a parameter... }, 1000); }, // CORRECT - always use get() for current state saveAnswer: async (questionId: string, value: number) => { await someAsyncOperation(); // After await, use get() to ensure current state const currentAnswers = get().answers; set({ answers: { ...currentAnswers, [questionId]: value } }); }, })); // In components - same principle function Component() { const answers = useStore((s) => s.answers); const handleSave = async () => { await delay(1000); // answers here is stale! Captured at render time // Use getState() for current value const current = useStore.getState().answers; }; } ``` **Rule:** After any `await`, use `get()` or `getState()` - never rely on closure-captured values. --- ## Pattern: Async Actions in Stores **Problem:** Async actions need explicit `async/await` and careful state reads after awaits. ```typescript const useStore = create((set, get) => ({ loading: false, data: null, error: null, // WRONG - no async keyword, race condition prone fetchDataBad: (id: string) => { set({ loading: true }); api.fetch(id).then((data) => { set({ data, loading: false }); }); // Returns immediately, caller can't await }, // CORRECT - proper async action fetch