React / Next.js standards (baseline)
Precedence. This is the fallback for an app that is not organised as feature slices. Where the app
has src/features/<Domain> slices over a shared ApiClient, route through frontend-registry —
frontend-architecture, frontend-design-system, frontend-seo, and frontend-testing are
authoritative there and define the FSD layout, ApiClient, styling system, and test setup.
Use this skill only for the general correctness rules below that those skills do not cover.
A repo's own skills and CLAUDE.md outrank both sets.
Otherwise: project conventions win. Check next.config, tsconfig.json, ESLint config, and existing
components first. Do not introduce a second state library, styling approach, or data-fetching pattern
alongside one that already exists — in particular, do not reach for Tailwind in a project built on
CSS variables and component classes.
TypeScript
strict: true. Noany— useunknownplus narrowing, or a real type.ascasts need a reason.- Type props explicitly; don't rely on inference across a module boundary.
- Discriminated unions over optional-flag soup:
type State = {status:'idle'} | {status:'loading'} | {status:'error', error:Error} | {status:'ok', data:T}. - Validate anything crossing a trust boundary (API responses,
searchParams, form data, env) with Zod — a TS type is a compile-time claim, not a runtime guarantee.
Server vs Client components (App Router)
This is the decision that most often goes wrong. Default is Server Component.
- Add
'use client'only for: event handlers,useState/useEffect/useReducer, browser APIs, or a client-only library. Push it to the leaf, not the page/layout. - A client component cannot import a server component as a child, but it can accept one via
children/props — use that to keep providers thin. - Never import server-only code (DB client, secrets, API keys) into a module reachable from a client
component. Mark such modules
import 'server-only'. - Fetch data in server components with
awaitdirectly. Do notuseEffect+fetchfor initial page data in the App Router. - Control caching deliberately:
fetch(url, { cache: 'force-cache' | 'no-store' })orexport const revalidate = N. State the choice — don't leave it implicit and then wonder why data is stale. - Mutations use Server Actions (
'use server') or route handlers, followed byrevalidatePath/revalidateTag. A server action is a public HTTP endpoint: authenticate and authorize inside it, every time. Never assume it can only be called from your own UI.
Components and hooks
- One component per file, named export, colocated with its styles/tests. Keep components under ~150 lines; extract when a component grows a second responsibility.
- Derive state, don't duplicate it. If a value is computable from props/state, compute it — no
useEffectthat syncs one piece of state to another. useEffectis for synchronizing with something outside React (subscriptions, DOM, timers). Data fetching, transformations, and event responses do not belong there.- Complete dependency arrays. Fix the design rather than silencing the lint rule.
- Stable
keyfrom entity id — never array index for reorderable/filterable lists. - Cleanup in effects: abort in-flight fetches (
AbortController), clear timers, remove listeners. useMemo/useCallback/memoonly after an actual measured problem, or to keep a referential identity that a dependency array needs. Not by default.
Data and state
- Server state (anything that lives in the backend) → one server-state library: the one the app already uses (TanStack Query, SWR,
RTK Query); if it has none, default to RTK Query (
createApi, features add endpoints withinjectEndpoints,providesTags/invalidatesTagsdeclared once). Never mirror server state into a slice/Context, and never hand-roll it withuseEffect+useStateorcreateAsyncThunk+extraReducersloading flags. Writes are that library's mutations. - Client state → the app's existing store (default: Redux Toolkit
createSlice), synchronous UI state only (wizard step, selection, toggles). Never API responses or hand-written loading/error flags. Never a second store library beside the first. Local state stays local; lift only as far as needed. createAsyncThunkonly for multi-step client orchestration:signalandrejectWithValuerequired, typed serialisable errors.- Typing: explicit types for every request, response and DTO; no
any, noRecord<string, any>; deriveRootState/AppDispatchonce and use only typed hooks (useAppSelector,useAppDispatch). - Global errors: wrap the base query once (401/expiry, retry only transient failures, serialisable errors);
error.tsx,not-found.tsx, and an Error Boundary around each independent feature module. - Forms: unsubmitted fields and validation errors in local state or React Hook Form + Zod, never Redux.
- Context is for dependency injection and low-frequency globals (theme, locale, session): split state from dispatch, memoise the value.
- Per-request isolation:
makeStore()factory, held by a Client ComponentStoreProvider(useRef), never a module-level singleton. - Prefetch in a Server Component and seed the per-request store when the client also reads the data; run independent reads in parallel.
- Pass
AbortSignalto every request. Writes: Server Action +revalidatePath/revalidateTag, or an RTK Query mutation + tag invalidation. - Selectors:
createSelectorfor derived/filtered Redux data,selectFromResultfor query results; neveruseSelector(s => s). NEXT_PUBLIC_*is public; secrets unprefixed and server-only; nothing secret or personal in Redux state. Detailed patterns: thereference/files of thefrontend-architectureskill.- URL is state: filters, tabs, pagination belong in
searchParamsso the view is shareable and back/forward works. - Every async view handles all four states: loading, empty, error, success. Use
loading.tsxanderror.tsx(client component withreset) at the route level. For the full failure path — boundary placement,global-error.tsx, server-action failures, the status→UX map, server validation onto form fields, retry/offline — load [[error-handling-frontend]], which applies to this baseline too.
Forms
- react-hook-form +
zodResolver, sharing the same Zod schema with server-side validation. - Native
<form>semantics; labels tied to inputs; disable submit while pending; show field-level errors wired viaaria-describedbyandaria-invalid. - Server-side validation is authoritative. Client validation is a UX affordance only.
Performance
next/imagefor images (never a raw<img>for content images);next/fontfor fonts.next/dynamicfor heavy client-only widgets (modals, data grids, charts, editors, maps), called from a Client Component (a dynamic import in a Server Component does not code-split client code); measure the gain.<Suspense>with a real skeleton, not a spinner-only page.- Watch bundle cost: don't import a whole library for one helper (
import debounce from 'lodash/debounce', notimport { debounce } from 'lodash'); preferdate-fns/Intlover moment. - Stream where it helps:
<Suspense>around slow sections so the shell paints immediately.
Accessibility
- Semantic elements first. A
<div onClick>is a bug — use<button>. - Keyboard reachable, visible focus, logical tab order; focus moves into dialogs and returns on close.
- Images: meaningful
alt, oralt=""when decorative. Icon-only buttons needaria-label. - Don't encode meaning in colour alone; text contrast ≥ 4.5:1.
Security
NEXT_PUBLIC_*is public. Anything in it ships to the browser. Server-only secrets get an unprefixed name and are read only in server code.- Never
dangerouslySetInnerHTMLwith content you did not author. If unavoidable, sanitize with DOMPurify — and prefer rendering as text. - Never build a URL for
fetch/redirect from raw user input without an allowlist (open redirect, SSRF). - Tokens in
httpOnly,Secure,SameSitecookies — notlocalStorage. - Authorization decisions belong on the server. Hiding a button is presentation, not access control.
- Never render backend error details or stack traces to the user.
- Keep a Content-Security-Policy in
next.config/ middleware; avoidunsafe-inlinescripts.
Testing
- Vitest/Jest + React Testing Library. Query by role and accessible name — not test-ids or class names.
- Test what the user does, not implementation details. MSW for network stubbing.
- Playwright for the handful of critical end-to-end flows (auth, checkout, primary create path).