`.
- **Keyboard reachable**: implicit when using semantic elements.
- **Visible focus**: `focus-visible:ring-2 ring-offset-2` (or equivalent). Never strip the outline without replacing it.
- **Accessible name**: visible text inside the element IS the name. Add `aria-label` ONLY for icon-only buttons (e.g., `
`); 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 (
{(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 ? ... : ...`.