Architect-level guidance for structuring React web applications — framework choice (Next.js 16 with Cache Components, React Router v8 framework or data mode, TanStack Start, Vite SPA), feature-first folder layout, state management chosen by lifetime (TanStack Query, URL, Zustand, Jotai, Redux Toolkit, Context), data layer and API contracts, routing and code splitting, auth and security boundaries, monorepos and design systems, and architecture decision records.
When agents use itUse this whenever the user is starting a React project, restructuring a large React codebase, choosing between state libraries, asks "Next.js or Vite", "monorepo or not", where a file or feature should live, how to share a component library across teams, or "how should I structure this" for anything React on the web. Also use it when a single component question hides a platform decision such as SSR, caching, session handling or a server/client boundary. For React Native use react-native-architecture.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill react-architecture -a github-copilot
# or with the org installer (adds .github/skills/react-architecture):
npx -y github:AGCO-Global/org-skills add skill react-architecture
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the frontend-react-skills plugin, which bundles all Frontend / React skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install frontend-react-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill react-architecture -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill react-architecture -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill react-architecture -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill react-architecture -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the react-architecture folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
Think like the engineer who will still own this codebase in three years: every choice trades short-term convenience for long-term clarity, and every choice is written down with the condition that would flip it. Give the decision, the one flipping condition, and the why — never "it depends" alone.
1. Decide first
Question
Default
Change when
Framework
Next.js 16 (App Router, cacheComponents: true) when you need Server Components, streaming, edge or partial prerendering
Want SSR + loaders without vendor coupling → React Router v8 framework mode (or TanStack Start). Pure SPA behind login, no SEO → Vite + React Router v8 data mode. Content/marketing → Astro with React islands. Never "Remix": Remix v2 became React Router v7 framework mode; Remix 3 is not a React framework.
Rendering
Server Components by default; 'use client' only at interaction boundaries
SPA: everything is client — do not fake SSR
Compiler
React Compiler on (reactCompiler: true in Next.js, babel-plugin-react-compiler in Vite)
Build time budget is tight on a huge legacy app → enable per directory first
State
By lifetime (§3): server data in a query cache or on the server, never in a client store
Only the row in the table changes, never "because Redux is standard"
Styling
Tailwind + headless primitives (Radix / React Aria), or the existing design system
Design tokens come from a design tool as CSS variables → CSS Modules on those tokens
Auth session
Cookie-based session read on the server (Server Component / loader / proxy.ts); client gets a serialisable user prop
Third-party SPA without a BFF → token in memory, refresh via HTTP-only cookie; never localStorage
Write these into ARCHITECTURE.md as ADRs (§9). Contributors, human and AI, read that first.
2. Folder structure: feature-first
Type-first (components/, hooks/, utils/) collapses at ~50 components. Use feature slices — src/app/ (routes only, thin), src/features/<feature>/{components,hooks,api,model,index.ts}, src/shared/{ui,lib,hooks}, optional src/entities/. A feature's index.ts is its only public import path; shared/ never imports from features/. Enforce with eslint-plugin-boundaries or no-restricted-imports; CI fails on violation. Full tree, Next.js/React Router variants and the monorepo layout: references/layouts.md.
3. State: choose by lifetime, not popularity
State kind
Tool
Why
Server data (anything with a URL)
TanStack Query v5 in SPAs; Server Components + 'use cache' or loader in frameworks
Caching, dedup, revalidation are solved; never in Redux/Zustand
Server-derived UI state (session, feature flags, permissions)
Read on the server, pass as props, expose via a small Context
Changes rarely; must be available before first paint
URL state (filters, pagination, tab)
Search params (nuqs in Next.js, useSearchParams in React Router)
Shareable, back-button friendly
Form state
React Hook Form + Zod (or Server Action + useActionState)
Context is for injection; every consumer re-renders on change
4. Data layer
Types from the contract: OpenAPI → openapi-typescript, GraphQL → codegen, tRPC for full-stack TS. Hand-written response types drift.
One apiClient in shared/lib (base URL, auth, error normalisation, AbortSignal). Features never call fetch directly.
Query keys as factories (orderKeys.list(filters)); mutations invalidate by prefix; Zod-validate responses from backends you do not own.
Next.js 16: caching is opt-in — 'use cache' + cacheLife/cacheTag, updateTag in Server Actions, revalidateTag(tag, profile) elsewhere; there is no implicit fetch cache and unstable_cache is replaced. references/nextjs-16.md.
React Router v8: loader/action per route module, clientLoader for cache-first reads, middleware for auth. references/react-router-8.md.
5. Routing, code splitting, loading
Every route is its own chunk: automatic in Next.js and React Router framework mode; lazy route objects in data mode.
Load data before render (Server Component, loader, prefetched query) — no mount-then-fetch waterfalls; parallelise with Promise.all.
Error boundary and loading UI per route segment (error.tsx/loading.tsx, ErrorBoundary/HydrateFallback exports); one root boundary reports to monitoring.
Prefetch likely next routes on hover or viewport (<Link prefetch>); keep 'use client' subtrees small because a boundary ships its whole module graph.
6. Security boundaries
import 'server-only' in every module that touches secrets, the database or internal APIs; client-only for window code. Never import a DB client from a 'use client' file.
Validate every Server Action and action input with Zod and authorise inside the action — it is a public endpoint.
NEXT_PUBLIC_* / VITE_* variables are shipped to the browser; everything else stays server-side. Next.js request interception lives in proxy.ts (Node runtime; middleware.ts deprecated).
Sanitise HTML (DOMPurify) before dangerouslySetInnerHTML; validate user-supplied href (no javascript:).
7. Composition rules
Compound components (<Card.Header/>) over eight-prop APIs; colocate data fetching with the component that renders it; lift state only to the lowest common ancestor; children for slots; one named export per file. Server Component by default and push interactivity into leaves.
8. Scaling to many teams
Turborepo or Nx with apps/ and packages/ (ui, config-eslint, tsconfig); packages built with tsup/tsdown; a versioned design system in packages/ui with Storybook that features never fork. Module Federation only when independent deploys are a hard requirement. Layout in references/layouts.md.
9. Deliverable format (ADR)
## ADR-<n>: <decision>
Context: <constraints: team, hosting, SEO, auth, existing code>
Decision: <default from the table, or the deviation>
Flips when: <the one condition that would change it>
Consequences: <what becomes easy, what becomes hard, migration cost>
Checklist
ARCHITECTURE.md holds the §1 decisions as ADRs and the folder convention
Framework choice names the flipping condition; no "Remix" recommendation
Feature slices with index.ts public APIs; ESLint boundary rule in CI
Server data in a query cache or server render, never in a client store
Caching in Next.js is explicit ('use cache', cacheLife, tags); no unstable_cache or implicit fetch cache assumptions
server-only guards secrets; Server Action inputs validated and authorised
Every route has an error boundary and loading UI; data loads before render
React Compiler on; tsc --noEmit, lint and tests gate CI
Env config validated at startup (Zod on process.env)
Anti-patterns
Circular feature imports or shared/ importing features/ → promote the shared piece to shared/ or entities/.
One global store holding server data → query cache; store keeps client state only.
Route files containing business logic → route renders a feature screen; logic in model/.
Barrel index.ts re-exporting all of shared/ → barrels only as feature public APIs; deep barrels defeat tree-shaking.
'use client' on a layout "to be safe" → mark the leaf that needs it.
Shared React anti-patterns: react-anti-patterns.md in ../react-development/references/.
---
name: react-architecture
description: >
Architect-level guidance for structuring React web applications — framework choice (Next.js 16 with Cache
Components, React Router v8 framework or data mode, TanStack Start, Vite SPA), feature-first folder layout,
state management chosen by lifetime (TanStack Query, URL, Zustand, Jotai, Redux Toolkit, Context), data layer
and API contracts, routing and code splitting, auth and security boundaries, monorepos and design systems,
and architecture decision records. Use this whenever the user is starting a React project, restructuring a
large React codebase, choosing between state libraries, asks "Next.js or Vite", "monorepo or not", where a
file or feature should live, how to share a component library across teams, or "how should I structure this"
for anything React on the web. Also use it when a single component question hides a platform decision such
as SSR, caching, session handling or a server/client boundary. For React Native use react-native-architecture.
metadata:
technology: React
type: architecture
---
# React Architecture
> **Targets:** React 19.2 · Next.js 16 · React Router v8 · TanStack Query v5 · Node 22 · **Verified:** 2026-09 against https://nextjs.org, https://reactrouter.com, https://react.dev
Think like the engineer who will still own this codebase in three years: every choice trades short-term convenience for long-term clarity, and every choice is written down with the condition that would flip it. Give the decision, the one flipping condition, and the why — never "it depends" alone.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| Framework | **Next.js 16** (App Router, `cacheComponents: true`) when you need Server Components, streaming, edge or partial prerendering | Want SSR + loaders without vendor coupling → **React Router v8 framework mode** (or TanStack Start). Pure SPA behind login, no SEO → **Vite + React Router v8 data mode**. Content/marketing → Astro with React islands. Never "Remix": Remix v2 became React Router v7 framework mode; Remix 3 is not a React framework. |
| Rendering | Server Components by default; `'use client'` only at interaction boundaries | SPA: everything is client — do not fake SSR |
| Compiler | React Compiler on (`reactCompiler: true` in Next.js, `babel-plugin-react-compiler` in Vite) | Build time budget is tight on a huge legacy app → enable per directory first |
| State | By lifetime (§3): server data in a query cache or on the server, never in a client store | Only the row in the table changes, never "because Redux is standard" |
| Styling | Tailwind + headless primitives (Radix / React Aria), or the existing design system | Design tokens come from a design tool as CSS variables → CSS Modules on those tokens |
| Auth session | Cookie-based session read on the server (Server Component / `loader` / `proxy.ts`); client gets a serialisable `user` prop | Third-party SPA without a BFF → token in memory, refresh via HTTP-only cookie; never `localStorage` |
| Package manager and language | pnpm workspaces; TypeScript `strict`; ESM-only deps (React Router v8, Node 22 baseline) | Existing monorepo standard |
| i18n | Route- or locale-segment based (`/[locale]/…`), `Intl` for dates and numbers, messages in `features/<f>/i18n/` | Single-locale internal tool → skip routing, keep `Intl` |
Write these into `ARCHITECTURE.md` as ADRs (§9). Contributors, human and AI, read that first.
## 2. Folder structure: feature-first
Type-first (`components/`, `hooks/`, `utils/`) collapses at ~50 components. Use feature slices — `src/app/` (routes only, thin), `src/features/<feature>/{components,hooks,api,model,index.ts}`, `src/shared/{ui,lib,hooks}`, optional `src/entities/`. A feature's `index.ts` is its only public import path; `shared/` never imports from `features/`. Enforce with `eslint-plugin-boundaries` or `no-restricted-imports`; CI fails on violation. Full tree, Next.js/React Router variants and the monorepo layout: `references/layouts.md`.
## 3. State: choose by lifetime, not popularity
| State kind | Tool | Why |
|---|---|---|
| Server data (anything with a URL) | **TanStack Query v5** in SPAs; Server Components + `'use cache'` or `loader` in frameworks | Caching, dedup, revalidation are solved; never in Redux/Zustand |
| Server-derived UI state (session, feature flags, permissions) | Read on the server, pass as props, expose via a small Context | Changes rarely; must be available before first paint |
| URL state (filters, pagination, tab) | Search params (`nuqs` in Next.js, `useSearchParams` in React Router) | Shareable, back-button friendly |
| Form state | React Hook Form + Zod (or Server Action + `useActionState`) | Uncontrolled inputs, schema-driven |
| Local UI (open/closed, hover) | `useState` / `useReducer` | Nothing else |
| Ephemeral cross-page UI (toasts, dialogs, wizard draft, cart) | **Zustand** (simple) or **Jotai** (atomic, derived) | Small, selector-based, works outside React |
| Event-sourced, audited, time-travel state | **Redux Toolkit** | Only when middleware and action logs are a requirement |
| Dependency injection (services, theme, query client) | React Context, rarely changing | Context is for injection; every consumer re-renders on change |
## 4. Data layer
- Types from the contract: OpenAPI → `openapi-typescript`, GraphQL → codegen, tRPC for full-stack TS. Hand-written response types drift.
- One `apiClient` in `shared/lib` (base URL, auth, error normalisation, `AbortSignal`). Features never call `fetch` directly.
- Query keys as factories (`orderKeys.list(filters)`); mutations invalidate by prefix; Zod-validate responses from backends you do not own.
- Next.js 16: caching is opt-in — `'use cache'` + `cacheLife`/`cacheTag`, `updateTag` in Server Actions, `revalidateTag(tag, profile)` elsewhere; there is no implicit `fetch` cache and `unstable_cache` is replaced. `references/nextjs-16.md`.
- React Router v8: `loader`/`action` per route module, `clientLoader` for cache-first reads, `middleware` for auth. `references/react-router-8.md`.
## 5. Routing, code splitting, loading
- Every route is its own chunk: automatic in Next.js and React Router framework mode; `lazy` route objects in data mode.
- Load data before render (Server Component, `loader`, prefetched query) — no mount-then-fetch waterfalls; parallelise with `Promise.all`.
- Error boundary and loading UI per route segment (`error.tsx`/`loading.tsx`, `ErrorBoundary`/`HydrateFallback` exports); one root boundary reports to monitoring.
- Prefetch likely next routes on hover or viewport (`<Link prefetch>`); keep `'use client'` subtrees small because a boundary ships its whole module graph.
## 6. Security boundaries
- `import 'server-only'` in every module that touches secrets, the database or internal APIs; `client-only` for `window` code. Never import a DB client from a `'use client'` file.
- Validate every Server Action and `action` input with Zod and authorise inside the action — it is a public endpoint.
- `NEXT_PUBLIC_*` / `VITE_*` variables are shipped to the browser; everything else stays server-side. Next.js request interception lives in `proxy.ts` (Node runtime; `middleware.ts` deprecated).
- Sanitise HTML (DOMPurify) before `dangerouslySetInnerHTML`; validate user-supplied `href` (no `javascript:`).
## 7. Composition rules
Compound components (`<Card.Header/>`) over eight-prop APIs; colocate data fetching with the component that renders it; lift state only to the lowest common ancestor; `children` for slots; one named export per file. Server Component by default and push interactivity into leaves.
## 8. Scaling to many teams
Turborepo or Nx with `apps/` and `packages/` (`ui`, `config-eslint`, `tsconfig`); packages built with `tsup`/`tsdown`; a versioned design system in `packages/ui` with Storybook that features never fork. Module Federation only when independent deploys are a hard requirement. Layout in `references/layouts.md`.
## 9. Deliverable format (ADR)
```
## ADR-<n>: <decision>
Context: <constraints: team, hosting, SEO, auth, existing code>
Decision: <default from the table, or the deviation>
Flips when: <the one condition that would change it>
Consequences: <what becomes easy, what becomes hard, migration cost>
```
## Checklist
- [ ] `ARCHITECTURE.md` holds the §1 decisions as ADRs and the folder convention
- [ ] Framework choice names the flipping condition; no "Remix" recommendation
- [ ] Feature slices with `index.ts` public APIs; ESLint boundary rule in CI
- [ ] Server data in a query cache or server render, never in a client store
- [ ] Caching in Next.js is explicit (`'use cache'`, `cacheLife`, tags); no `unstable_cache` or implicit `fetch` cache assumptions
- [ ] `server-only` guards secrets; Server Action inputs validated and authorised
- [ ] Every route has an error boundary and loading UI; data loads before render
- [ ] React Compiler on; `tsc --noEmit`, lint and tests gate CI
- [ ] Env config validated at startup (Zod on `process.env`)
## Anti-patterns
- **Circular feature imports or `shared/` importing `features/`** → promote the shared piece to `shared/` or `entities/`.
- **One global store holding server data** → query cache; store keeps client state only.
- **Route files containing business logic** → route renders a feature screen; logic in `model/`.
- **Barrel `index.ts` re-exporting all of `shared/`** → barrels only as feature public APIs; deep barrels defeat tree-shaking.
- **`'use client'` on a layout "to be safe"** → mark the leaf that needs it.
- Shared React anti-patterns: `react-anti-patterns.md` in `../react-development/references/`.
## Go deeper
- `references/nextjs-16.md` — Cache Components, `'use cache'`, `cacheLife`/`cacheTag`, `updateTag`/`revalidateTag`, `proxy.ts`, async `params`, `next/image` defaults, migration from 15.
- `references/react-router-8.md` — v8 upgrade facts, route module API, modes, middleware, when to pick it over Next.js.
- `references/layouts.md` — feature-first tree for Next.js, React Router and Expo, monorepo layout, boundary ESLint config.
- Sibling skills: `react-development`, `react-performance`, `react-testing`, `frontend-code-review`, `react-native-architecture`.