# 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 // Prefetch follows the project's policy. Where the project turns viewport // prefetching off (it costs container CPU/RAM), pass prefetch={false} and // comment each link that opts back in: View gallery // primary funnel CTA — prefetch is intentional Checkout // 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 import { cn } from "@/lib/utils"; 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 (fallback: no OpenAPI spec) **Default path is orval-generated hooks** when the project has an OpenAPI spec: run the project's `gen:api` task and import the generated `useQuery`/`useMutation` hooks instead of writing this by hand (see `tech-stack.md` §Server State). Auth headers belong in the orval `mutator` instance, not per-hook. The pattern below is for spec-less endpoints only (third-party APIs, endpoints outside the contract). ```tsx import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; // getToken(): placeholder for the project's auth helper // (e.g. better-auth client session); wire to the real token source. 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 Pass the zod schema directly to `validators` (Standard Schema, v1+). `validatorAdapter` / `@tanstack/zod-form-adapter` are dead v0 APIs; never reintroduce them. Errors are issue **objects**, not strings: render `errors[0]?.message`. ```tsx "use client"; import { useForm } from "@tanstack/react-form"; import { z } from "zod"; // zod v4: z.email() replaces the deprecated z.string().email() const schema = z.object({ email: z.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: "" }, 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.isValid} /> {/* Standard Schema errors are issue objects; render .message, never the object */} {!field.state.meta.isValid && (

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

)}
)}
{(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.isValid} /> {!field.state.meta.isValid && (

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

)}
)}
[state.canSubmit, state.isSubmitting]}> {([canSubmit, isSubmitting]) => ( )}
); } ``` --- ## i18n: never hardcode UI text UI strings come from the project's i18n source of truth (`packages/i18n` or equivalent). Adapt the accessor to the project's library (next-intl, react-i18next, lingui, etc.); the invariants below hold regardless of library. ```tsx // next-intl example; swap for the project's i18n hook import { useTranslations } from "next-intl"; export function CheckoutSummary({ itemCount }: { itemCount: number }) { const t = useTranslations("checkout"); return (

{t("title")}

{/* plurals/interpolation go through the library, never string concatenation */}

{t("itemCount", { count: itemCount })}

); } ``` Invariants: - **No hardcoded user-facing strings** in JSX, `aria-*`, `alt`, `title`, placeholders, or toasts; all of them are translatable surfaces. - **Add new keys to the i18n source of truth first**, in every supported locale (fallback locale at minimum); never inline a "temporary" English string. - **No string concatenation for sentences**: word order differs per language; use interpolation with named params. - **Plurals via the library's plural rules** (`count`-style params), not `count === 1 ? ... : ...`.