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
Pagination and Infinite Scroll

Pagination and Infinite Scroll

Implement efficient pagination patterns in Google Antigravity with cursor-based and infinite scroll.

paginationinfinite-scrollperformanceux
by antigravity-team
⭐0Stars
.antigravity
# Pagination Patterns for Google Antigravity

Implement efficient pagination with cursor-based, offset, and infinite scroll patterns.

## Cursor-Based Pagination

```typescript
// lib/pagination.ts
import { createClient } from "@/lib/supabase/server";

interface PaginatedResult<T> {
    data: T[];
    nextCursor: string | null;
    hasMore: boolean;
}

export async function fetchWithCursor<T>(
    table: string,
    cursor: string | null,
    limit: number = 20,
    orderBy: string = "created_at"
): Promise<PaginatedResult<T>> {
    const supabase = createClient();
    let query = supabase.from(table).select("*").order(orderBy, { ascending: false }).limit(limit + 1);

    if (cursor) {
        query = query.lt(orderBy, cursor);
    }

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

    const hasMore = data.length > limit;
    const items = hasMore ? data.slice(0, -1) : data;
    const nextCursor = hasMore ? items[items.length - 1][orderBy] : null;

    return { data: items as T[], nextCursor, hasMore };
}
```

## Infinite Scroll Hook

```typescript
// hooks/useInfiniteScroll.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";

interface UseInfiniteScrollOptions<T> {
    fetchFn: (cursor: string | null) => Promise<{ data: T[]; nextCursor: string | null; hasMore: boolean }>;
    threshold?: number;
}

export function useInfiniteScroll<T>({ fetchFn, threshold = 200 }: UseInfiniteScrollOptions<T>) {
    const [items, setItems] = useState<T[]>([]);
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const cursorRef = useRef<string | null>(null);
    const observerRef = useRef<IntersectionObserver | null>(null);

    const loadMore = useCallback(async () => {
        if (loading || !hasMore) return;
        setLoading(true);
        try {
            const result = await fetchFn(cursorRef.current);
            setItems((prev) => [...prev, ...result.data]);
            cursorRef.current = result.nextCursor;
            setHasMore(result.hasMore);
        } catch (error) {
            console.error("Failed to load more:", error);
        } finally {
            setLoading(false);
        }
    }, [fetchFn, loading, hasMore]);

    const lastItemRef = useCallback((node: HTMLElement | null) => {
        if (loading) return;
        if (observerRef.current) observerRef.current.disconnect();
        observerRef.current = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting && hasMore) loadMore();
        }, { rootMargin: `${threshold}px` });
        if (node) observerRef.current.observe(node);
    }, [loading, hasMore, loadMore, threshold]);

    useEffect(() => { loadMore(); }, []);

    const reset = useCallback(() => {
        setItems([]);
        cursorRef.current = null;
        setHasMore(true);
        loadMore();
    }, [loadMore]);

    return { items, loading, hasMore, lastItemRef, loadMore, reset };
}
```

## Infinite Scroll Component

```typescript
// components/InfiniteList.tsx
"use client";

import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";

interface Post {
    id: string;
    title: string;
    content: string;
    created_at: string;
}

export function InfinitePostList() {
    const { items, loading, hasMore, lastItemRef } = useInfiniteScroll<Post>({
        fetchFn: async (cursor) => {
            const params = new URLSearchParams({ limit: "20" });
            if (cursor) params.set("cursor", cursor);
            const response = await fetch(`/api/posts?${params}`);
            return response.json();
        },
    });

    return (
        <div className="post-list">
            {items.map((post, index) => (
                <article key={post.id} ref={index === items.length - 1 ? lastItemRef : null} className="post-card">
                    <h2>{post.title}</h2>
                    <p>{post.content.substring(0, 150)}...</p>
                </article>
            ))}
            {loading && <div className="loading">Loading more...</div>}
            {!hasMore && items.length > 0 && <div className="end">No more posts</div>}
        </div>
    );
}
```

## Offset Pagination

```typescript
// lib/offset-pagination.ts
import { createClient } from "@/lib/supabase/server";

interface OffsetPaginatedResult<T> {
    data: T[];
    total: number;
    page: number;
    pageSize: number;
    totalPages: number;
}

export async function fetchWithOffset<T>(
    table: string,
    page: number = 1,
    pageSize: number = 20
): Promise<OffsetPaginatedResult<T>> {
    const supabase = createClient();
    const from = (page - 1) * pageSize;
    const to = from + pageSize - 1;

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

    if (error) throw error;

    return {
        data: data as T[],
        total: count || 0,
        page,
        pageSize,
        totalPages: Math.ceil((count || 0) / pageSize),
    };
}
```

## Pagination Controls

```typescript
// components/Pagination.tsx
"use client";

import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";

interface PaginationProps {
    currentPage: number;
    totalPages: number;
}

export function Pagination({ currentPage, totalPages }: PaginationProps) {
    const pathname = usePathname();
    const searchParams = useSearchParams();

    const createPageURL = (page: number) => {
        const params = new URLSearchParams(searchParams);
        params.set("page", page.toString());
        return `${pathname}?${params.toString()}`;
    };

    const pages = getPageNumbers(currentPage, totalPages);

    return (
        <nav className="pagination" aria-label="Pagination">
            <Link href={createPageURL(currentPage - 1)} className={`page-link ${currentPage === 1 ? "disabled" : ""}`} aria-disabled={currentPage === 1}>Previous</Link>
            {pages.map((page, i) => (
                page === "..." ? <span key={i} className="ellipsis">...</span> :
                <Link key={page} href={createPageURL(page as number)} className={`page-link ${currentPage === page ? "active" : ""}`} aria-current={currentPage === page ? "page" : undefined}>{page}</Link>
            ))}
            <Link href={createPageURL(currentPage + 1)} className={`page-link ${currentPage === totalPages ? "disabled" : ""}`} aria-disabled={currentPage === totalPages}>Next</Link>
        </nav>
    );
}

function getPageNumbers(current: number, total: number): (number | string)[] {
    if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1);
    if (current <= 3) return [1, 2, 3, 4, "...", total];
    if (current >= total - 2) return [1, "...", total - 3, total - 2, total - 1, total];
    return [1, "...", current - 1, current, current + 1, "...", total];
}
```

## API Route

```typescript
// app/api/posts/route.ts
import { NextRequest, NextResponse } from "next/server";
import { fetchWithCursor } from "@/lib/pagination";

export async function GET(request: NextRequest) {
    const cursor = request.nextUrl.searchParams.get("cursor");
    const limit = parseInt(request.nextUrl.searchParams.get("limit") || "20");

    const result = await fetchWithCursor("posts", cursor, limit);
    return NextResponse.json(result);
}
```

## Best Practices

1. **Cursor vs Offset**: Use cursor for large datasets
2. **Stable Ordering**: Ensure consistent sort order
3. **Prefetching**: Prefetch next page for smoother UX
4. **Skeleton Loading**: Show skeletons while loading
5. **Error Recovery**: Handle errors gracefully

When to Use This Prompt

This pagination prompt is ideal for developers working on:

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

Related Prompts

💬 Comments

Loading comments...