Optimize React and Next.js applications with code splitting, lazy loading, caching strategies, and Core Web Vitals improvements.
# Performance Optimization for Google Antigravity
Building performant applications is crucial for user experience and SEO. This guide covers performance optimization strategies optimized for Google Antigravity and Gemini 3 development.
## Code Splitting and Dynamic Imports
Implement intelligent code splitting:
```typescript
// components/LazyComponents.tsx
import dynamic from "next/dynamic";
import { Suspense } from "react";
// Heavy components loaded on demand
const HeavyChart = dynamic(() => import("./HeavyChart"), {
loading: () => <ChartSkeleton />,
ssr: false, // Client-only component
});
const MarkdownEditor = dynamic(
() => import("./MarkdownEditor").then((mod) => mod.MarkdownEditor),
{
loading: () => <EditorSkeleton />,
}
);
const DataTable = dynamic(() => import("./DataTable"), {
loading: () => <TableSkeleton />,
});
// Preload on hover for faster perceived performance
export function PreloadableLink({
href,
children,
preloadComponent
}: {
href: string;
children: React.ReactNode;
preloadComponent?: () => Promise<unknown>;
}) {
const handleMouseEnter = () => {
if (preloadComponent) {
preloadComponent();
}
};
return (
<Link href={href} onMouseEnter={handleMouseEnter}>
{children}
</Link>
);
}
// Usage
export function Dashboard() {
return (
<div>
<Suspense fallback={<ChartSkeleton />}>
<HeavyChart data={chartData} />
</Suspense>
<Suspense fallback={<TableSkeleton />}>
<DataTable rows={tableData} />
</Suspense>
</div>
);
}
```
## Image Optimization
Implement comprehensive image optimization:
```typescript
// components/OptimizedImage.tsx
import Image from "next/image";
import { useState } from "react";
interface OptimizedImageProps {
src: string;
alt: string;
width: number;
height: number;
priority?: boolean;
className?: string;
}
export function OptimizedImage({
src,
alt,
width,
height,
priority = false,
className,
}: OptimizedImageProps) {
const [isLoading, setIsLoading] = useState(true);
return (
<div className={`relative overflow-hidden ${className}`}>
<Image
src={src}
alt={alt}
width={width}
height={height}
priority={priority}
loading={priority ? undefined : "lazy"}
placeholder="blur"
blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRg..."
className={`
duration-700 ease-in-out
${isLoading ? "scale-110 blur-2xl grayscale" : "scale-100 blur-0 grayscale-0"}
`}
onLoad={() => setIsLoading(false)}
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
);
}
// Responsive image with art direction
export function ResponsiveHero({ images }: { images: { mobile: string; desktop: string } }) {
return (
<picture>
<source media="(min-width: 768px)" srcSet={images.desktop} />
<Image
src={images.mobile}
alt="Hero image"
width={800}
height={600}
priority
className="w-full h-auto"
/>
</picture>
);
}
```
## Caching Strategies
Implement effective caching:
```typescript
// lib/cache/strategies.ts
import { unstable_cache } from "next/cache";
// Server-side caching with revalidation
export const getCachedPosts = unstable_cache(
async (category?: string) => {
const posts = await db.post.findMany({
where: category ? { category } : undefined,
orderBy: { createdAt: "desc" },
take: 20,
});
return posts;
},
["posts"],
{
revalidate: 60, // Revalidate every minute
tags: ["posts"],
}
);
// API route with cache headers
export async function GET(request: Request) {
const data = await getCachedPosts();
return Response.json(data, {
headers: {
"Cache-Control": "public, s-maxage=60, stale-while-revalidate=300",
},
});
}
// Client-side caching with SWR
import useSWR from "swr";
const fetcher = (url: string) => fetch(url).then((res) => res.json());
export function useCachedData<T>(key: string) {
const { data, error, isLoading, mutate } = useSWR<T>(key, fetcher, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
dedupingInterval: 60000,
});
return { data, error, isLoading, refresh: mutate };
}
```
## Bundle Size Optimization
Analyze and optimize bundle size:
```typescript
// next.config.ts
const nextConfig = {
experimental: {
optimizePackageImports: [
"lodash",
"date-fns",
"@heroicons/react",
"lucide-react",
],
},
webpack: (config, { isServer }) => {
// Replace large libraries with smaller alternatives
config.resolve.alias = {
...config.resolve.alias,
"lodash": "lodash-es",
};
// Analyze bundle in development
if (process.env.ANALYZE === "true") {
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: "static",
reportFilename: isServer
? "../analyze/server.html"
: "./analyze/client.html",
})
);
}
return config;
},
};
```
## Best Practices
When optimizing performance in Antigravity projects, measure Core Web Vitals regularly, use React DevTools Profiler, implement progressive loading, optimize third-party scripts, use font-display swap, minimize layout shifts, lazy load below-fold content, and set up performance monitoring with real user metrics.This Performance prompt is ideal for developers working on:
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 performance implementations.
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.
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.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Performance projects, consider mentioning your framework version, coding style, and any specific libraries you're using.