Build lightweight scalable state management with Zustand in Google Antigravity including persistence middleware and slices
# Zustand Store Architecture Patterns for Google Antigravity
State management should be simple yet powerful. Zustand provides a minimalist approach that scales elegantly. This guide establishes patterns for using Zustand with Google Antigravity projects, enabling Gemini 3 to generate clean, performant state management implementations.
## Store Creation
Create typed stores with proper structure:
```typescript
// stores/useAuthStore.ts
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";
interface User {
id: string;
email: string;
name: string;
avatarUrl?: string;
}
interface AuthState {
user: User | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
}
interface AuthActions {
login: (email: string, password: string) => Promise<void>;
logout: () => void;
updateProfile: (updates: Partial<User>) => void;
clearError: () => void;
}
type AuthStore = AuthState & AuthActions;
export const useAuthStore = create<AuthStore>()(
persist(
immer((set, get) => ({
user: null,
isAuthenticated: false,
isLoading: false,
error: null,
login: async (email, password) => {
set({ isLoading: true, error: null });
try {
const response = await fetch("/api/auth/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!response.ok) throw new Error("Login failed");
const { user } = await response.json();
set({ user, isAuthenticated: true, isLoading: false });
} catch (error) {
set({ error: error instanceof Error ? error.message : "Login failed", isLoading: false });
}
},
logout: () => set({ user: null, isAuthenticated: false, error: null }),
updateProfile: (updates) => set((state) => { if (state.user) Object.assign(state.user, updates); }),
clearError: () => set({ error: null }),
})),
{ name: "auth-storage", storage: createJSONStorage(() => localStorage) }
)
);
```
## Slice Pattern for Large Stores
Organize with slices:
```typescript
// stores/slices/cartSlice.ts
import { StateCreator } from "zustand";
export interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
export interface CartSlice {
items: CartItem[];
addItem: (item: Omit<CartItem, "quantity">) => void;
removeItem: (id: string) => void;
getTotal: () => number;
}
export const createCartSlice: StateCreator<CartSlice> = (set, get) => ({
items: [],
addItem: (item) => set((state) => {
const existing = state.items.find((i) => i.id === item.id);
if (existing) {
return { items: state.items.map((i) => i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i) };
}
return { items: [...state.items, { ...item, quantity: 1 }] };
}),
removeItem: (id) => set((state) => ({ items: state.items.filter((i) => i.id !== id) })),
getTotal: () => get().items.reduce((sum, item) => sum + item.price * item.quantity, 0),
});
```
## Selective Subscriptions
Optimize re-renders:
```typescript
import { useStore } from "@/stores/useStore";
import { shallow } from "zustand/shallow";
export function CartIcon() {
const itemCount = useStore((state) => state.items.reduce((sum, i) => sum + i.quantity, 0));
return <span className="badge">{itemCount}</span>;
}
export function CartSummary() {
const { items, total } = useStore(
(state) => ({ items: state.items.length, total: state.getTotal() }),
shallow
);
return <p>{items} items - ${total}</p>;
}
```
## Best Practices
1. **Single store with slices**: Organize by feature
2. **Selective subscriptions**: Prevent unnecessary re-renders
3. **Immer middleware**: Simplify immutable updates
4. **Persist selectively**: Only store essential data
5. **TypeScript**: Fully type stores and actionsThis 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.