Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver ToolsFeatured on FazierFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowAI ToolzShinyLaunchMillion Dot HomepageSolver Tools

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Zustand State Management

Zustand State Management

Lightweight state management with Zustand including middleware, persistence, and TypeScript patterns

ZustandReactState ManagementTypeScript
by Antigravity Team
⭐0Stars
.antigravity
# 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.

When to Use This Prompt

This Zustand prompt is ideal for developers working on:

  • Zustand applications requiring modern best practices and optimal performance
  • Projects that need production-ready Zustand code with proper error handling
  • Teams looking to standardize their zustand development workflow
  • Developers wanting to learn industry-standard Zustand patterns and techniques

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.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the Zustand code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this Zustand prompt commercially?

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.

Which AI assistants work best with this prompt?

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.

How do I customize this prompt for my specific needs?

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.

Related Prompts

💬 Comments

Loading comments...