Build lightweight, scalable state management with Zustand in Google Antigravity applications with TypeScript and persistence.
# Zustand Store Patterns
Implement lightweight, scalable state management with Zustand in your Google Antigravity applications. This guide covers store patterns, middleware, persistence, and TypeScript integration.
## Basic Store Setup
Create a typed Zustand store:
```typescript
// stores/useAppStore.ts
import { create } from "zustand";
import { devtools, persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
interface AppState {
theme: "light" | "dark" | "system";
sidebarOpen: boolean;
notifications: Notification[];
}
interface AppActions {
setTheme: (theme: AppState["theme"]) => void;
toggleSidebar: () => void;
addNotification: (notification: Omit<Notification, "id">) => void;
removeNotification: (id: string) => void;
clearNotifications: () => void;
}
export const useAppStore = create<AppState & AppActions>()(
devtools(
persist(
immer((set) => ({
// State
theme: "system",
sidebarOpen: true,
notifications: [],
// Actions
setTheme: (theme) =>
set((state) => {
state.theme = theme;
}),
toggleSidebar: () =>
set((state) => {
state.sidebarOpen = !state.sidebarOpen;
}),
addNotification: (notification) =>
set((state) => {
state.notifications.push({
...notification,
id: crypto.randomUUID(),
});
}),
removeNotification: (id) =>
set((state) => {
state.notifications = state.notifications.filter((n) => n.id !== id);
}),
clearNotifications: () =>
set((state) => {
state.notifications = [];
}),
})),
{
name: "app-storage",
partialize: (state) => ({ theme: state.theme }),
}
),
{ name: "AppStore" }
)
);
```
## Slice Pattern
Organize large stores with slices:
```typescript
// stores/slices/userSlice.ts
import { StateCreator } from "zustand";
export interface UserSlice {
user: User | null;
isLoading: boolean;
setUser: (user: User | null) => void;
fetchUser: () => Promise<void>;
}
export const createUserSlice: StateCreator<
UserSlice & CartSlice,
[],[],
UserSlice
> = (set, get) => ({
user: null,
isLoading: false,
setUser: (user) => set({ user }),
fetchUser: async () => {
set({ isLoading: true });
try {
const response = await fetch("/api/user");
const user = await response.json();
set({ user, isLoading: false });
} catch (error) {
set({ user: null, isLoading: false });
}
},
});
// stores/useStore.ts
import { create } from "zustand";
import { createUserSlice, UserSlice } from "./slices/userSlice";
import { createCartSlice, CartSlice } from "./slices/cartSlice";
export const useStore = create<UserSlice & CartSlice>()((...a) => ({
...createUserSlice(...a),
...createCartSlice(...a),
}));
```
## Selectors for Performance
Optimize re-renders with selectors:
```typescript
// stores/selectors.ts
import { useAppStore } from "./useAppStore";
import { shallow } from "zustand/shallow";
// Single selector
export const useTheme = () => useAppStore((state) => state.theme);
// Multiple selectors with shallow comparison
export const useNotifications = () =>
useAppStore(
(state) => ({
notifications: state.notifications,
addNotification: state.addNotification,
removeNotification: state.removeNotification,
}),
shallow
);
// Computed selectors
export const useUnreadCount = () =>
useAppStore((state) => state.notifications.filter((n) => !n.read).length);
```
## Async Actions
Handle async operations in stores:
```typescript
// stores/usePromptStore.ts
import { create } from "zustand";
import { createClient } from "@/lib/supabase/client";
interface PromptStore {
prompts: Prompt[];
isLoading: boolean;
error: string | null;
fetchPrompts: () => Promise<void>;
createPrompt: (data: CreatePromptData) => Promise<void>;
deletePrompt: (id: string) => Promise<void>;
}
export const usePromptStore = create<PromptStore>((set, get) => ({
prompts: [],
isLoading: false,
error: null,
fetchPrompts: async () => {
set({ isLoading: true, error: null });
try {
const supabase = createClient();
const { data, error } = await supabase
.from("prompts")
.select("*")
.order("created_at", { ascending: false });
if (error) throw error;
set({ prompts: data, isLoading: false });
} catch (error) {
set({ error: (error as Error).message, isLoading: false });
}
},
deletePrompt: async (id) => {
const previousPrompts = get().prompts;
// Optimistic update
set((state) => ({
prompts: state.prompts.filter((p) => p.id !== id),
}));
try {
const supabase = createClient();
const { error } = await supabase.from("prompts").delete().eq("id", id);
if (error) throw error;
} catch (error) {
// Rollback on error
set({ prompts: previousPrompts, error: (error as Error).message });
}
},
}));
```
## Best Practices
1. **Atomic Selectors**: Use fine-grained selectors to prevent unnecessary re-renders
2. **Slice Pattern**: Split large stores into manageable slices
3. **Immer Middleware**: Use immer for complex state updates
4. **Persistence**: Persist only necessary state to storage
5. **DevTools**: Enable devtools in development for debugging
6. **TypeScript**: Fully type stores for better DXThis zustand prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their zustand implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For zustand projects, consider mentioning your framework version, coding style, and any specific libraries you're using.