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 Store Patterns

Zustand Store Patterns

Build lightweight, scalable state management with Zustand in Google Antigravity applications with TypeScript and persistence.

zustandstate-managementreacttypescriptperformance
by antigravity-team
⭐0Stars
.antigravity
# 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 DX

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...