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.

\n\n
\n

Hello, {name}!

\n

Count: {count}

\n \n \n \n
\n```\n\n## Derived State with $derived\n\nCompute values that depend on other state:\n\n```svelte\n\n\n\n
\n

Shopping Cart ({itemCount} items)

\n \n {#each items as item (item.id)}\n
\n {item.name}\n ${item.price.toFixed(2)}\n
\n \n {item.quantity}\n \n
\n \n
\n {/each}\n \n
\n

Subtotal: ${subtotal.toFixed(2)}

\n

Tax: ${tax.toFixed(2)}

\n

Total: {formattedTotal}

\n
\n
\n```\n\n## Side Effects with $effect\n\nHandle side effects reactively:\n\n```svelte\n\n\n\n
\n \n \n {#if error}\n

{error}

\n {:else if isLoading}\n

Searching...

\n {:else if results.length > 0}\n
    \n {#each results as result (result.id)}\n
  • \n \n {result.title}\n

    {result.description}

    \n
    \n
  • \n {/each}\n
\n {:else if query.length >= 2}\n

No results found

\n {/if}\n
\n```\n\n## Props with $props\n\nDefine component props with runes:\n\n```svelte\n\n\n\n
\n

{prompt.title}

\n \n {#if variant !== 'compact'}\n

{prompt.description}

\n {/if}\n \n
\n {#each prompt.tags as tag}\n {tag}\n {/each}\n
\n \n {#if showAuthor && prompt.author}\n
\n {prompt.author.name}\n {prompt.author.name}\n
\n {/if}\n \n
\n \n
\n
\n```\n\n## Bindable Props with $bindable\n\nCreate two-way binding props:\n\n```svelte\n\n\n\n\n\n{#if open}\n
\n
e.stopPropagation()}>\n
\n

{title}

\n \n
\n
\n {@render children()}\n
\n
\n
\n{/if}\n\n\n\n\n\n\n\n

Are you sure you want to continue?

\n \n \n
\n```\n\n## Stores with Runes\n\nCreate shared state stores:\n\n```typescript\n// stores/user.svelte.ts\nimport type { User } from '@/lib/types';\n\nclass UserStore {\n user = $state(null);\n isLoading = $state(false);\n \n isAuthenticated = $derived(this.user !== null);\n displayName = $derived(this.user?.name ?? 'Guest');\n\n async login(email: string, password: string) {\n this.isLoading = true;\n try {\n const response = await fetch('/api/auth/login', {\n method: 'POST',\n body: JSON.stringify({ email, password }),\n });\n this.user = await response.json();\n } finally {\n this.isLoading = false;\n }\n }\n\n logout() {\n this.user = null;\n }\n}\n\nexport const userStore = new UserStore();\n```\n\n## Best Practices\n\n1. **Use $state for reactive values** that change over time\n2. **Use $derived for computed values** that depend on state\n3. **Use $effect for side effects** like API calls and subscriptions\n4. **Clean up effects** by returning cleanup functions\n5. **Use $props for component inputs** with TypeScript types\n6. **Create stores as classes** with $state properties\n7. **Avoid unnecessary effects** - prefer derived state when possible","author":{"@type":"Person","name":"Antigravity Team"},"dateCreated":"2026-01-04T00:21:26.302757+00:00","keywords":"svelte, runes, state-management, reactive, frontend","programmingLanguage":"Antigravity AI Prompt","codeRepository":"https://antigravityai.directory"}
Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
Svelte 5 Runes State Management

Svelte 5 Runes State Management

Reactive state management with Svelte 5 runes for Google Antigravity projects including $state, $derived, and $effect patterns.

svelterunesstate-managementreactivefrontend
by Antigravity Team
⭐0Stars
.antigravity
# Svelte 5 Runes State Management for Google Antigravity

Master reactive state management with Svelte 5 runes in your Google Antigravity IDE projects. This comprehensive guide covers $state, $derived, $effect, and component patterns optimized for Gemini 3 agentic development.

## Basic State with $state

Create reactive state using the $state rune:

```svelte
<!-- components/Counter.svelte -->
<script lang="ts">
  let count = $state(0);
  let name = $state('World');
  
  function increment() {
    count++;
  }
  
  function decrement() {
    count--;
  }
</script>

<div class="counter">
  <h2>Hello, {name}!</h2>
  <p>Count: {count}</p>
  <button onclick={decrement}>-</button>
  <button onclick={increment}>+</button>
  <input bind:value={name} placeholder="Your name" />
</div>
```

## Derived State with $derived

Compute values that depend on other state:

```svelte
<!-- components/Cart.svelte -->
<script lang="ts">
  interface CartItem {
    id: string;
    name: string;
    price: number;
    quantity: number;
  }

  let items = $state<CartItem[]>([
    { id: '1', name: 'Prompt Pack', price: 9.99, quantity: 1 },
    { id: '2', name: 'MCP Server', price: 19.99, quantity: 2 },
  ]);

  // Derived values automatically update
  let itemCount = $derived(items.reduce((sum, item) => sum + item.quantity, 0));
  let subtotal = $derived(items.reduce((sum, item) => sum + item.price * item.quantity, 0));
  let tax = $derived(subtotal * 0.1);
  let total = $derived(subtotal + tax);

  // Derived with complex logic
  let formattedTotal = $derived.by(() => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(total);
  });

  function updateQuantity(id: string, delta: number) {
    const item = items.find((i) => i.id === id);
    if (item) {
      item.quantity = Math.max(0, item.quantity + delta);
      if (item.quantity === 0) {
        items = items.filter((i) => i.id !== id);
      }
    }
  }

  function removeItem(id: string) {
    items = items.filter((i) => i.id !== id);
  }
</script>

<div class="cart">
  <h2>Shopping Cart ({itemCount} items)</h2>
  
  {#each items as item (item.id)}
    <div class="cart-item">
      <span>{item.name}</span>
      <span>${item.price.toFixed(2)}</span>
      <div class="quantity">
        <button onclick={() => updateQuantity(item.id, -1)}>-</button>
        <span>{item.quantity}</span>
        <button onclick={() => updateQuantity(item.id, 1)}>+</button>
      </div>
      <button onclick={() => removeItem(item.id)}>Remove</button>
    </div>
  {/each}
  
  <div class="totals">
    <p>Subtotal: ${subtotal.toFixed(2)}</p>
    <p>Tax: ${tax.toFixed(2)}</p>
    <p class="total">Total: {formattedTotal}</p>
  </div>
</div>
```

## Side Effects with $effect

Handle side effects reactively:

```svelte
<!-- components/Search.svelte -->
<script lang="ts">
  import { debounce } from '@/lib/utils';

  interface SearchResult {
    id: string;
    title: string;
    description: string;
  }

  let query = $state('');
  let results = $state<SearchResult[]>([]);
  let isLoading = $state(false);
  let error = $state<string | null>(null);

  // Effect runs when dependencies change
  $effect(() => {
    if (query.length < 2) {
      results = [];
      return;
    }

    const controller = new AbortController();
    
    async function search() {
      isLoading = true;
      error = null;
      
      try {
        const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
          signal: controller.signal,
        });
        
        if (!response.ok) throw new Error('Search failed');
        
        const data = await response.json();
        results = data.results;
      } catch (e) {
        if (e instanceof Error && e.name !== 'AbortError') {
          error = e.message;
        }
      } finally {
        isLoading = false;
      }
    }

    // Debounce search
    const timeoutId = setTimeout(search, 300);

    // Cleanup function runs before next effect
    return () => {
      clearTimeout(timeoutId);
      controller.abort();
    };
  });

  // Effect for localStorage sync
  $effect(() => {
    localStorage.setItem('lastSearch', query);
  });

  // Pre-effect runs before DOM updates
  $effect.pre(() => {
    console.log('About to update with', results.length, 'results');
  });
</script>

<div class="search">
  <input
    type="search"
    bind:value={query}
    placeholder="Search prompts..."
    class:loading={isLoading}
  />
  
  {#if error}
    <p class="error">{error}</p>
  {:else if isLoading}
    <p>Searching...</p>
  {:else if results.length > 0}
    <ul class="results">
      {#each results as result (result.id)}
        <li>
          <a href="/prompts/{result.id}">
            <strong>{result.title}</strong>
            <p>{result.description}</p>
          </a>
        </li>
      {/each}
    </ul>
  {:else if query.length >= 2}
    <p>No results found</p>
  {/if}
</div>
```

## Props with $props

Define component props with runes:

```svelte
<!-- components/PromptCard.svelte -->
<script lang="ts">
  import type { Prompt } from '@/lib/types';

  interface Props {
    prompt: Prompt;
    variant?: 'default' | 'compact' | 'featured';
    showAuthor?: boolean;
    onStar?: (id: string) => void;
  }

  let {
    prompt,
    variant = 'default',
    showAuthor = true,
    onStar,
  }: Props = $props();

  let isStarred = $state(false);

  async function handleStar() {
    isStarred = !isStarred;
    onStar?.(prompt.id);
  }
</script>

<article class="prompt-card" class:compact={variant === 'compact'} class:featured={variant === 'featured'}>
  <h3>{prompt.title}</h3>
  
  {#if variant !== 'compact'}
    <p>{prompt.description}</p>
  {/if}
  
  <div class="tags">
    {#each prompt.tags as tag}
      <span class="tag">{tag}</span>
    {/each}
  </div>
  
  {#if showAuthor && prompt.author}
    <div class="author">
      <img src={prompt.author.image} alt={prompt.author.name} />
      <span>{prompt.author.name}</span>
    </div>
  {/if}
  
  <div class="actions">
    <button onclick={handleStar} class:starred={isStarred}>
      {isStarred ? '★' : '☆'} {prompt.starCount}
    </button>
  </div>
</article>
```

## Bindable Props with $bindable

Create two-way binding props:

```svelte
<!-- components/Modal.svelte -->
<script lang="ts">
  interface Props {
    open: boolean;
    title: string;
    children: import('svelte').Snippet;
    onClose?: () => void;
  }

  let { open = $bindable(false), title, children, onClose }: Props = $props();

  function close() {
    open = false;
    onClose?.();
  }

  function handleKeydown(event: KeyboardEvent) {
    if (event.key === 'Escape') close();
  }
</script>

<svelte:window onkeydown={handleKeydown} />

{#if open}
  <div class="modal-backdrop" onclick={close}>
    <div class="modal" onclick={(e) => e.stopPropagation()}>
      <header>
        <h2>{title}</h2>
        <button onclick={close} aria-label="Close">×</button>
      </header>
      <div class="modal-content">
        {@render children()}
      </div>
    </div>
  </div>
{/if}

<!-- Usage -->
<script>
  let showModal = $state(false);
</script>

<button onclick={() => showModal = true}>Open Modal</button>

<Modal bind:open={showModal} title="Confirm Action">
  <p>Are you sure you want to continue?</p>
  <button onclick={() => showModal = false}>Cancel</button>
  <button onclick={confirm}>Confirm</button>
</Modal>
```

## Stores with Runes

Create shared state stores:

```typescript
// stores/user.svelte.ts
import type { User } from '@/lib/types';

class UserStore {
  user = $state<User | null>(null);
  isLoading = $state(false);
  
  isAuthenticated = $derived(this.user !== null);
  displayName = $derived(this.user?.name ?? 'Guest');

  async login(email: string, password: string) {
    this.isLoading = true;
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      });
      this.user = await response.json();
    } finally {
      this.isLoading = false;
    }
  }

  logout() {
    this.user = null;
  }
}

export const userStore = new UserStore();
```

## Best Practices

1. **Use $state for reactive values** that change over time
2. **Use $derived for computed values** that depend on state
3. **Use $effect for side effects** like API calls and subscriptions
4. **Clean up effects** by returning cleanup functions
5. **Use $props for component inputs** with TypeScript types
6. **Create stores as classes** with $state properties
7. **Avoid unnecessary effects** - prefer derived state when possible

When to Use This Prompt

This svelte prompt is ideal for developers working on:

  • svelte applications requiring modern best practices and optimal performance
  • Projects that need production-ready svelte code with proper error handling
  • Teams looking to standardize their svelte development workflow
  • Developers wanting to learn industry-standard svelte 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 svelte 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 svelte 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 svelte 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 svelte projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...