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
React Query Data Fetching Patterns

React Query Data Fetching Patterns

Master server state management with TanStack Query in Google Antigravity applications for caching, mutations, and optimistic updates.

tanstack-queryreact-querydata-fetchingcachingreact
by antigravity-team
⭐0Stars
.antigravity
# React Query Data Fetching Patterns

Build efficient data fetching layers with TanStack Query (React Query) in your Google Antigravity applications. This guide covers queries, mutations, caching strategies, and optimistic updates.

## Query Client Setup

Configure TanStack Query with sensible defaults:

```typescript
// lib/query-client.ts
import { QueryClient } from "@tanstack/react-query";

export function makeQueryClient() {
  return new QueryClient({
    defaultOptions: {
      queries: {
        staleTime: 60 * 1000, // 1 minute
        gcTime: 10 * 60 * 1000, // 10 minutes
        retry: (failureCount, error) => {
          if (error instanceof Response && error.status === 404) {
            return false;
          }
          return failureCount < 3;
        },
        refetchOnWindowFocus: false,
      },
      mutations: {
        retry: 1,
      },
    },
  });
}

// app/providers.tsx
"use client";

import { QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { useState } from "react";
import { makeQueryClient } from "@/lib/query-client";

export function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(() => makeQueryClient());

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}
```

## Query Hooks

Create reusable query hooks:

```typescript
// hooks/usePrompts.ts
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { createClient } from "@/lib/supabase/client";

export const promptKeys = {
  all: ["prompts"] as const,
  lists: () => [...promptKeys.all, "list"] as const,
  list: (filters: PromptFilters) => [...promptKeys.lists(), filters] as const,
  details: () => [...promptKeys.all, "detail"] as const,
  detail: (id: string) => [...promptKeys.details(), id] as const,
};

export function usePrompts(filters: PromptFilters = {}) {
  return useQuery({
    queryKey: promptKeys.list(filters),
    queryFn: async () => {
      const supabase = createClient();
      let query = supabase
        .from("prompts")
        .select("*")
        .eq("is_approved", true)
        .order("created_at", { ascending: false });

      if (filters.category) {
        query = query.contains("tags", [filters.category]);
      }

      const { data, error } = await query;
      if (error) throw error;
      return data;
    },
  });
}

export function usePrompt(id: string) {
  return useQuery({
    queryKey: promptKeys.detail(id),
    queryFn: async () => {
      const supabase = createClient();
      const { data, error } = await supabase
        .from("prompts")
        .select("*")
        .eq("id", id)
        .single();

      if (error) throw error;
      return data;
    },
    enabled: !!id,
  });
}
```

## Mutations with Optimistic Updates

Implement optimistic updates for instant feedback:

```typescript
// hooks/useStarPrompt.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { promptKeys } from "./usePrompts";

export function useStarPrompt() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({ promptId, userId }: { promptId: string; userId: string }) => {
      const supabase = createClient();
      const { error } = await supabase
        .from("stars")
        .insert({ prompt_id: promptId, user_id: userId });
      if (error) throw error;
    },
    onMutate: async ({ promptId }) => {
      await queryClient.cancelQueries({ queryKey: promptKeys.detail(promptId) });
      const previousPrompt = queryClient.getQueryData<Prompt>(
        promptKeys.detail(promptId)
      );
      if (previousPrompt) {
        queryClient.setQueryData(promptKeys.detail(promptId), {
          ...previousPrompt,
          star_count: previousPrompt.star_count + 1,
          is_starred: true,
        });
      }
      return { previousPrompt };
    },
    onError: (err, { promptId }, context) => {
      if (context?.previousPrompt) {
        queryClient.setQueryData(
          promptKeys.detail(promptId),
          context.previousPrompt
        );
      }
    },
    onSettled: (_, __, { promptId }) => {
      queryClient.invalidateQueries({ queryKey: promptKeys.detail(promptId) });
    },
  });
}
```

## Infinite Queries

Implement infinite scrolling:

```typescript
// hooks/useInfinitePrompts.ts
import { useInfiniteQuery } from "@tanstack/react-query";

export function useInfinitePrompts() {
  return useInfiniteQuery({
    queryKey: ["prompts", "infinite"],
    queryFn: async ({ pageParam = 0 }) => {
      const supabase = createClient();
      const limit = 20;
      const from = pageParam * limit;
      const to = from + limit - 1;

      const { data, error, count } = await supabase
        .from("prompts")
        .select("*", { count: "exact" })
        .eq("is_approved", true)
        .order("created_at", { ascending: false })
        .range(from, to);

      if (error) throw error;
      return { data, nextPage: to < (count || 0) - 1 ? pageParam + 1 : undefined };
    },
    getNextPageParam: (lastPage) => lastPage.nextPage,
    initialPageParam: 0,
  });
}
```

## Best Practices

1. **Query Keys**: Use structured query key factories for consistency
2. **Stale Time**: Set appropriate stale times based on data freshness needs
3. **Optimistic Updates**: Provide instant feedback for better UX
4. **Error Handling**: Implement proper error boundaries and retry logic
5. **Prefetching**: Prefetch data on hover for perceived performance
6. **Devtools**: Use React Query Devtools during development

When to Use This Prompt

This tanstack-query prompt is ideal for developers working on:

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

Related Prompts

💬 Comments

Loading comments...