# Frontend Agent - Code Snippets Copy-paste ready patterns. Use these as starting points, adapt to the specific task. --- ## Next.js 16 framework canonicals (use these — never the legacy alternatives) ```tsx // ✅ Internal nav: , never import Link from "next/link"; View gallery // ✅ Custom font: next/font, never import { Inter } from "next/font/google"; const inter = Inter({ subsets: ["latin"] }); ... // ✅ Images: next/image, never raw import Image from "next/image"; Hero scene // ✅ Imports: only what you use. After refactoring, remove orphans. // ✅ useCallback / useEffect deps: list every referenced symbol exactly. ``` --- ## Accessible Card (focus ring + semantic + keyboard) Baseline for an interactive surface. Adjust colors via theme tokens; verify the resulting contrast ratio against the actual `--card` / `--foreground` / `--muted-foreground` values (theme tokens alone do NOT guarantee 4.5:1 — the designer / token system has to make them so). ```tsx interface CardProps { title: string; description?: string; onClick?: () => void; } export function Card({ title, description, onClick }: CardProps) { return ( ); } ``` Accessibility checklist for interactive surfaces: - **Semantic element** — ``); when visible text exists, `aria-label` overrides it and is an anti-pattern. - **Contrast** — verify the actual color values against background reach 4.5:1 (normal text) or 3:1 (large text >= 18pt or 14pt bold). Run an axe/Lighthouse pass; theme tokens are not a proof. - **Heading semantics** — keep heading tags (`

`-`

`) outside interactive elements. Inside a button, use `` with type-scale classes; promote to a heading at the surrounding section level. --- ## React 19 hook patterns ```tsx // ✅ Derive in render — no state, no effect function ItemCount({ items }: { items: Item[] }) { const count = items.length; return {count}; } // ✅ Initialize once with a lazy initializer const [id] = useState(() => crypto.randomUUID()); // ✅ Pass the ref OBJECT (not its current value) to children that need an instance. // The child reads .current inside its own effect or event handler, never in render. function Selectable({ targetRef }: { targetRef: React.RefObject }) { // ... } // ❌ Never: useEffect that calls setState to mirror props/state // eslint: react-hooks/set-state-in-effect // useEffect(() => { setCount(items.length); }, [items]); // ❌ Never: gate JSX on ref.current — it is null on first render, and refs // do not trigger re-renders when they attach // eslint: react-hooks/refs // return ref.current ? : null; ``` ## TanStack Query Hook ```tsx import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; interface Todo { id: string; title: string; completed: boolean; } export function useTodos() { return useQuery({ queryKey: ["todos"], queryFn: async () => { const res = await fetch("/api/todos", { headers: { Authorization: `Bearer ${getToken()}` }, }); if (!res.ok) throw new Error("Failed to fetch"); return res.json(); }, }); } export function useCreateTodo() { const queryClient = useQueryClient(); return useMutation({ mutationFn: async (data: { title: string }) => { const res = await fetch("/api/todos", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}`, }, body: JSON.stringify(data), }); if (!res.ok) throw new Error("Failed to create"); return res.json(); }, onSuccess: () => queryClient.invalidateQueries({ queryKey: ["todos"] }), }); } ``` --- ## Form with TanStack Form + Zod ```tsx "use client"; import { useForm } from "@tanstack/react-form"; import { zodValidator } from "@tanstack/zod-form-adapter"; import { z } from "zod"; const schema = z.object({ email: z.string().email("Invalid email"), password: z.string().min(8, "At least 8 characters"), }); export function LoginForm({ onSubmit }: { onSubmit: (data: z.infer) => void }) { const form = useForm({ defaultValues: { email: "", password: "" }, validatorAdapter: zodValidator(), validators: { onChange: schema }, onSubmit: async ({ value }) => onSubmit(value), }); return (
{ e.preventDefault(); e.stopPropagation(); form.handleSubmit(); }} className="space-y-4" > {(field) => (
field.handleChange(e.target.value)} onBlur={field.handleBlur} className="mt-1 w-full rounded-md border px-3 py-2" aria-invalid={field.state.meta.errors.length > 0} /> {field.state.meta.errors.length > 0 && (

{field.state.meta.errors[0]}

)}
)}
{(field) => (
field.handleChange(e.target.value)} onBlur={field.handleBlur} className="mt-1 w-full rounded-md border px-3 py-2" aria-invalid={field.state.meta.errors.length > 0} /> {field.state.meta.errors.length > 0 && (

{field.state.meta.errors[0]}

)}
)}
[state.canSubmit, state.isSubmitting]}> {([canSubmit, isSubmitting]) => ( )}
); } ``` --- ## Loading / Error / Empty States ```tsx interface AsyncStateProps { data: T | undefined; isLoading: boolean; error: Error | null; empty: React.ReactNode; children: (data: T) => React.ReactNode; } export function AsyncState({ data, isLoading, error, empty, children }: AsyncStateProps) { if (isLoading) return
; if (error) return ; if (!data || (Array.isArray(data) && data.length === 0)) return <>{empty}; return <>{children(data)}; } ``` --- ## Responsive Grid Layout ```tsx export function StatsGrid({ children }: { children: React.ReactNode }) { return (
{children}
); } ``` --- ## Vitest Component Test ```tsx import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, it, expect, vi } from "vitest"; import { Card } from "./Card"; describe("Card", () => { it("renders title and description", () => { render(); expect(screen.getByText("Test")).toBeInTheDocument(); expect(screen.getByText("Desc")).toBeInTheDocument(); }); it("calls onClick when clicked", async () => { const onClick = vi.fn(); render(); await userEvent.click(screen.getByText("Test")); expect(onClick).toHaveBeenCalledOnce(); }); }); ```