Lightweight state management with Zustand including middleware, persistence, and TypeScript patterns
# Zustand State Management for Google Antigravity
Master lightweight state management with Zustand using Google Antigravity's Gemini 3 engine. This guide covers store creation, middleware, persistence, and TypeScript patterns for scalable applications.
## Store Creation
```typescript
// stores/auth-store.ts
import { create } from 'zustand';
import { devtools, persist, subscribeWithSelector } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
interface User {
id: string;
email: string;
name: string;
role: string;
}
interface AuthState {
user: User | null;
token: string | null;
isLoading: boolean;
error: string | null;
}
interface AuthActions {
setUser: (user: User | null) => void;
setToken: (token: string | null) => void;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
refreshToken: () => Promise<void>;
}
type AuthStore = AuthState & AuthActions;
export const useAuthStore = create<AuthStore>()(
devtools(
persist(
subscribeWithSelector(
immer((set, get) => ({
// State
user: null,
token: null,
isLoading: false,
error: null,
// Actions
setUser: (user) =>
set((state) => {
state.user = user;
}),
setToken: (token) =>
set((state) => {
state.token = token;
}),
login: async (email, password) => {
set((state) => {
state.isLoading = true;
state.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, token } = await response.json();
set((state) => {
state.user = user;
state.token = token;
state.isLoading = false;
});
} catch (error) {
set((state) => {
state.error = error instanceof Error ? error.message : 'Login failed';
state.isLoading = false;
});
throw error;
}
},
logout: () => {
set((state) => {
state.user = null;
state.token = null;
});
},
refreshToken: async () => {
const { token } = get();
if (!token) return;
try {
const response = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
});
if (!response.ok) {
get().logout();
return;
}
const { token: newToken } = await response.json();
set((state) => {
state.token = newToken;
});
} catch {
get().logout();
}
},
}))
),
{
name: 'auth-storage',
partialize: (state) => ({ user: state.user, token: state.token }),
}
),
{ name: 'AuthStore' }
)
);
```
## Cart Store with Computed Values
```typescript
// stores/cart-store.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
image?: string;
}
interface CartState {
items: CartItem[];
couponCode: string | null;
discount: number;
}
interface CartActions {
addItem: (item: Omit<CartItem, 'quantity'>) => void;
removeItem: (id: string) => void;
updateQuantity: (id: string, quantity: number) => void;
applyCoupon: (code: string) => Promise<boolean>;
removeCoupon: () => void;
clearCart: () => void;
}
interface CartComputed {
itemCount: () => number;
subtotal: () => number;
total: () => number;
}
type CartStore = CartState & CartActions & CartComputed;
export const useCartStore = create<CartStore>()(
persist(
immer((set, get) => ({
// State
items: [],
couponCode: null,
discount: 0,
// Actions
addItem: (item) =>
set((state) => {
const existing = state.items.find((i) => i.id === item.id);
if (existing) {
existing.quantity += 1;
} else {
state.items.push({ ...item, quantity: 1 });
}
}),
removeItem: (id) =>
set((state) => {
state.items = state.items.filter((i) => i.id !== id);
}),
updateQuantity: (id, quantity) =>
set((state) => {
const item = state.items.find((i) => i.id === id);
if (item) {
if (quantity <= 0) {
state.items = state.items.filter((i) => i.id !== id);
} else {
item.quantity = quantity;
}
}
}),
applyCoupon: async (code) => {
try {
const response = await fetch(`/api/coupons/validate?code=${code}`);
if (!response.ok) return false;
const { discount } = await response.json();
set((state) => {
state.couponCode = code;
state.discount = discount;
});
return true;
} catch {
return false;
}
},
removeCoupon: () =>
set((state) => {
state.couponCode = null;
state.discount = 0;
}),
clearCart: () =>
set((state) => {
state.items = [];
state.couponCode = null;
state.discount = 0;
}),
// Computed values (implemented as functions)
itemCount: () => get().items.reduce((sum, item) => sum + item.quantity, 0),
subtotal: () =>
get().items.reduce((sum, item) => sum + item.price * item.quantity, 0),
total: () => {
const subtotal = get().subtotal();
const discount = get().discount;
return subtotal - (subtotal * discount) / 100;
},
})),
{ name: 'cart-storage' }
)
);
```
## Store Slices Pattern
```typescript
// stores/slices/ui-slice.ts
import { StateCreator } from 'zustand';
export interface UISlice {
sidebarOpen: boolean;
theme: 'light' | 'dark' | 'system';
toggleSidebar: () => void;
setTheme: (theme: 'light' | 'dark' | 'system') => void;
}
export const createUISlice: StateCreator<UISlice> = (set) => ({
sidebarOpen: true,
theme: 'system',
toggleSidebar: () => set((state) => ({ sidebarOpen: !state.sidebarOpen })),
setTheme: (theme) => set({ theme }),
});
// stores/slices/notification-slice.ts
export interface Notification {
id: string;
message: string;
type: 'success' | 'error' | 'info';
}
export interface NotificationSlice {
notifications: Notification[];
addNotification: (notification: Omit<Notification, 'id'>) => void;
removeNotification: (id: string) => void;
}
export const createNotificationSlice: StateCreator<NotificationSlice> = (set) => ({
notifications: [],
addNotification: (notification) =>
set((state) => ({
notifications: [
...state.notifications,
{ ...notification, id: crypto.randomUUID() },
],
})),
removeNotification: (id) =>
set((state) => ({
notifications: state.notifications.filter((n) => n.id !== id),
})),
});
// stores/app-store.ts
import { create } from 'zustand';
import { createUISlice, UISlice } from './slices/ui-slice';
import { createNotificationSlice, NotificationSlice } from './slices/notification-slice';
type AppStore = UISlice & NotificationSlice;
export const useAppStore = create<AppStore>()((...a) => ({
...createUISlice(...a),
...createNotificationSlice(...a),
}));
```
## Subscribe to Store Changes
```typescript
// hooks/use-auth-sync.ts
import { useEffect } from 'react';
import { useAuthStore } from '@/stores/auth-store';
export function useAuthSync() {
useEffect(() => {
const unsubscribe = useAuthStore.subscribe(
(state) => state.token,
(token, prevToken) => {
if (token && !prevToken) {
console.log('User logged in');
} else if (!token && prevToken) {
console.log('User logged out');
}
}
);
return unsubscribe;
}, []);
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these Zustand patterns: Use immer middleware for immutable updates. Implement store slices for large applications. Persist only necessary state to storage. Use subscribeWithSelector for fine-grained subscriptions. Avoid storing server state in Zustand - use TanStack Query instead.This 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.