Skip to content

Lesson 15 of 28Architecture

React Architecture

Organise a React or Next.js app by feature, split server, client and URL state, layer the UI, and place server and error boundaries.

34 min read0/9 questions

Small React apps survive any structure. At 200 components, the questions change: where does this hook go, who owns this state, why does typing in a search box re-render the whole page? Good React architecture answers those questions before they become bugs, and "how would you structure a large React app?" is a staple of frontend interviews.

Group by feature, not by file type

There are two common ways to lay out src/.

Type-based puts all components in components/, all hooks in hooks/, all API calls in api/. It feels tidy at first. At scale, one feature (checkout) is smeared across six folders, and deleting it means hunting through all of them.

Feature-based puts everything for one feature in one folder: its components, hooks, API calls, types and tests. Shared building blocks live in a separate components/ui/. You can read, change or delete a feature in one place.

Feature-based Next.js app
  • src/
  • app/Next.js routes only: thin pages that compose features
  • layout.tsx
  • checkout/
  • page.tsxrenders <CheckoutPage />
  • orders/
  • page.tsx
  • features/
  • checkout/
  • components/
  • CheckoutPage.tsx
  • CartSummary.tsx
  • CartSummary.test.tsxcolocated test
  • hooks/
  • useCart.tslogic layer
  • api.tsdata access for this feature
  • types.ts
  • orders/
  • components/
  • hooks/
  • useOrders.tswraps TanStack Query
  • api.ts
  • components/
  • ui/shared primitives: Button, Tabs, Dialog
  • lib/
  • http.tsone fetch wrapper: base URL, auth, errors
  • stores/
  • session.tssmall global store (Zustand)

A rule that keeps this healthy: features may import from components/ui and lib, but not from each other's internals. If orders needs something from checkout, move it to shared code or export it deliberately from the feature's top level.

Quick check
Your team is removing the 'wishlist' feature. Which layout makes that a small, safe change?
Need a nudge? A hint rules out a wrong answer.

Presentational vs container, and what hooks changed

Around 2015 the advice was to split every component in two. A container fetched data and held state. A presentational component only received props and rendered markup. The split made UI easy to reuse and test.

Hooks moved the container's job into a custom hook. The logic still lives apart from the markup, but without an extra wrapper component. The custom hook is now your logic layer: it owns state, effects and calls to the data layer, and it can be tested on its own.

React
import { useState } from "react"; type Item = { sku: string; name: string; priceCents: number; qty: number }; // Logic layer: state + rules, no markupfunction useCart(initial: Item[]) { const [items, setItems] = useState(initial); const totalCents = items.reduce((sum, i) => sum + i.priceCents * i.qty, 0); const changeQty = (sku: string, delta: number) => setItems((prev) => prev.map((i) => (i.sku === sku ? { ...i, qty: i.qty + delta } : i)).filter((i) => i.qty > 0), ); return { items, totalCents, changeQty };} // Presentational: props in, markup outfunction CartLine({ item, onChange }: { item: Item; onChange: (delta: number) => void }) { return ( <li style={{ display: "flex", gap: 8, alignItems: "center" }}> <span style={{ flex: 1 }}>{item.name}</span> <button onClick={() => onChange(-1)}>-</button> <span>{item.qty}</span> <button onClick={() => onChange(1)}>+</button> </li> );} export default function App() { const cart = useCart([ { sku: "MUG", name: "Mug", priceCents: 1200, qty: 1 }, { sku: "CAP", name: "Cap", priceCents: 2000, qty: 2 }, ]); return ( <div style={{ fontFamily: "system-ui", maxWidth: 280 }}> <ul style={{ listStyle: "none", padding: 0, display: "grid", gap: 6 }}> {cart.items.map((item) => ( <CartLine key={item.sku} item={item} onChange={(d) => cart.changeQty(item.sku, d)} /> ))} </ul> <strong>Total: ${(cart.totalCents / 100).toFixed(2)}</strong> </div> );}

CartLine could render in a design system gallery with fake props. useCart could move to a server-synced version without CartLine changing.

Compound components

Some components are really a family that works together: tabs, accordions, menus, selects. A compound component exposes the parts separately (Tabs.List, Tabs.Tab, Tabs.Panel) and shares state between them through context, so the caller controls layout and content without a giant props object. Radix, Base UI and Headless UI all use this API.

React
import { createContext, useContext, useState } from "react"; const TabsContext = createContext<{ active: string; setActive: (v: string) => void } | null>(null); function useTabs() { const ctx = useContext(TabsContext); if (!ctx) throw new Error("Tabs parts must be used inside <Tabs>"); return ctx;} function Tabs({ defaultValue, children }: { defaultValue: string; children: React.ReactNode }) { const [active, setActive] = useState(defaultValue); return <TabsContext.Provider value={{ active, setActive }}>{children}</TabsContext.Provider>;} function TabList({ children }: { children: React.ReactNode }) { return <div role="tablist" style={{ display: "flex", gap: 4, marginBottom: 8 }}>{children}</div>;} function Tab({ value, children }: { value: string; children: React.ReactNode }) { const { active, setActive } = useTabs(); const selected = active === value; return ( <button role="tab" aria-selected={selected} onClick={() => setActive(value)} style={{ fontWeight: selected ? 700 : 400, borderBottom: selected ? "2px solid" : "2px solid transparent" }}> {children} </button> );} function Panel({ value, children }: { value: string; children: React.ReactNode }) { const { active } = useTabs(); return active === value ? <div role="tabpanel">{children}</div> : null;} Tabs.List = TabList;Tabs.Tab = Tab;Tabs.Panel = Panel; export default function App() { return ( <div style={{ fontFamily: "system-ui" }}> <Tabs defaultValue="card"> <Tabs.List> <Tabs.Tab value="card">Card</Tabs.Tab> <Tabs.Tab value="paypal">PayPal</Tabs.Tab> <Tabs.Tab value="invoice">Invoice</Tabs.Tab> </Tabs.List> <Tabs.Panel value="card">Pay now with Visa or Mastercard.</Tabs.Panel> <Tabs.Panel value="paypal">You will be redirected to PayPal.</Tabs.Panel> <Tabs.Panel value="invoice">Net 30. Business accounts only.</Tabs.Panel> </Tabs> </div> );}

The caller decides order, wrapping elements and content. Compare that with <Tabs items={[{ label, content, icon, disabled, badge }]} />, which grows a new prop for every request.

Quick check
How do Tabs.Tab and Tabs.Panel know which tab is active without the caller passing it to each one?
Need a nudge? A hint rules out a wrong answer.

Render props vs hooks

Before hooks, logic was shared with render props: a component that calls a function child with its data, like <MousePosition>{(pos) => <Cursor at={pos} />}</MousePosition>. It worked, but nesting three of them created a "pyramid" of callbacks. A hook does the same with a flat line: const pos = useMousePosition().

Render props still have a place when a component must control where something renders, such as a virtualised list calling renderRow(item) only for visible rows. For sharing logic, use hooks.

Where state should live

Put state as low as possible, and move it up only when you must. Each step up costs more re-renders and more coupling.

The state placement ladder
  1. Local stateuseState in the component that uses it: an open dropdown, a form field
  2. Lifted statemoved to the closest common parent of two siblings that need it
  3. Contextrarely-changing values many levels deep: theme, current user, locale
  4. Server cachedata that lives on the server: TanStack Query, SWR, or Next.js server components
  5. Global client storeZustand or Redux for true app-wide client state: a multi-step editor, a cart

Start here. Most state is used by one component. Keeping it local means typing in it re-renders only that component.

1/5
Match the pairs0/4 matched

Where should each piece of state live?

Choose an item, then its match on the other side.
Quick check
A team stores the text of a search box in a context provider at the root of the app. Typing now feels laggy on big pages. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

Server state is not client state

The ladder above has a rung that changes how you build everything else: server state. It is worth being precise about why it is different.

Client state is owned by the browser. Whether a dialog is open, what is typed in a draft, which step of a wizard you are on. It is always correct, because nothing else can change it.

Server state is owned by somebody else. The list of orders lives in a database, and what you hold in the browser is a copy that starts going stale the moment it arrives. Another tab, another user or a background job can change the real thing. So server state needs things client state never does: caching, deduplication of identical requests, refetching when the window regains focus, retries, and invalidation after you change something.

The classic mistake is to treat it as client state: useEffect fetches the orders and copies them into Redux or a context. Now you have hand-written loading flags, two components fetching the same list, and a refund that updates the server but leaves the list showing the old status. A server-state library such as TanStack Query handles all of that:

features/orders/hooks/useRefundOrder.ts
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ordersApi } from "../api";
import { orderKeys } from "../keys";
 
export function useRefundOrder() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ordersApi.refund,
    // The server changed, so every cached list or detail for orders is now suspect
    onSuccess: () => queryClient.invalidateQueries({ queryKey: orderKeys.all }),
  });
}
features/orders/keys.ts
export const orderKeys = {
  all: ["orders"] as const,
  list: (filters: { status: string; page: number }) => ["orders", "list", filters] as const,
  detail: (id: number) => ["orders", "detail", id] as const,
};

A query key factory like orderKeys is a small architectural decision that pays off. Keys are hierarchical, so invalidating ["orders"] refreshes every list and detail under it, and nobody types a key by hand in a component. The key also includes the filters, so page 2 of open orders and page 1 of closed orders are cached separately.

Two defaults are worth knowing. staleTime is 0 by default, so cached data counts as stale at once and is refetched in the background on the next mount or window focus, while the cached copy is shown instantly. Raise it for data that rarely changes. gcTime (five minutes by default) controls how long unused data stays in memory. Check the TanStack Query docs for the version you use.

Match the pairs0/4 matched

What kind of state is each of these?

Choose an item, then its match on the other side.

The URL is state too

There is a third home for state that teams forget: the URL. Filters, the selected tab, sort order, the page number and the search query are all state, and they belong in search params.

Putting them there gives you features for free:

  • Sharing and bookmarks. A support agent can paste /orders?status=open&page=3 to a colleague and they see the same screen.
  • Back and forward work. Each filter change can be a history entry, so the back button undoes it.
  • Refresh keeps your place. Nothing is lost when the page reloads or the app redeploys.
  • The server can render it. In the Next.js App Router, a page receives searchParams (a Promise you await in recent versions), so the first HTML already has the right rows.

The cost is that the URL is untrusted text. Anyone can type ?page=-3&status=banana. Treat search params like any other input: parse them in one function with defaults and validation, and serialise them back in one function that drops defaults so URLs stay clean.

TypeScript
type Status = "all" | "open" | "closed";type Sort = "newest" | "oldest";type Filters = { status: Status; sort: Sort; page: number; q: string }; const DEFAULTS: Filters = { status: "all", sort: "newest", page: 1, q: "" };const STATUSES: Status[] = ["all", "open", "closed"];const SORTS: Sort[] = ["newest", "oldest"]; function parseFilters(search: string): Filters { const p = new URLSearchParams(search); const status = p.get("status") as Status; const sort = p.get("sort") as Sort; const page = Number(p.get("page")); return { status: STATUSES.includes(status) ? status : DEFAULTS.status, sort: SORTS.includes(sort) ? sort : DEFAULTS.sort, page: Number.isInteger(page) && page > 0 ? page : DEFAULTS.page, q: p.get("q") ?? DEFAULTS.q, };} function toSearch(f: Filters): string { const p = new URLSearchParams(); for (const key of Object.keys(f) as (keyof Filters)[]) { if (f[key] !== DEFAULTS[key]) p.set(key, String(f[key])); } const s = p.toString(); return s ? `?${s}` : "";} console.log(parseFilters("?status=open&page=2"));console.log(parseFilters("?status=banana&page=-3&sort=oldest"));console.log(toSearch({ ...DEFAULTS, status: "closed", q: "late fee" }));console.log(JSON.stringify(toSearch(DEFAULTS)));
Output
Press Run (⌘ Enter) to see what happens.

In a client component you read the current values with useSearchParams() and update them with router.replace() (or push() if each change should be its own history entry). The small nuqs library wraps this pattern with typed parsers if you need it in many places. Either way, the parsed Filters object is what goes into the query key, so the URL, the cache and the screen always agree.

Keep the URL for state a user would want to share or come back to. Hover states, an open tooltip or a half-typed form field do not belong there.

Predict the outputJavaScript

What does this print?

const p = new URLSearchParams({ status: "closed", page: "1", q: "late fee" });
p.delete("page");
console.log("?" + p.toString());
Need a nudge? Hints walk you through it.

A data access layer

Components should not call fetch directly. Give each feature an api.ts that knows URLs and response shapes, and wrap it in hooks:

features/orders/api.ts
import { http } from "@/lib/http";
import type { Order } from "./types";
 
export const ordersApi = {
  list: () => http.get<Order[]>("/api/orders"),
  refund: (id: number) => http.post<Order>(`/api/orders/${id}/refund`),
};
features/orders/hooks/useOrders.ts
import { useQuery } from "@tanstack/react-query";
import { ordersApi } from "../api";
 
export function useOrders() {
  return useQuery({ queryKey: ["orders"], queryFn: ordersApi.list });
}

Now components ask useOrders() and get { data, isPending, error }. When the backend renames a field, you fix api.ts, not 14 components. In a Next.js App Router app, server components call a server-only data function (getOrders() in features/orders/data.ts) directly instead, and the same rule holds: one module owns the data access.

Tests live next to the code they test (CartSummary.test.tsx beside CartSummary.tsx), usually with Vitest and Testing Library. Moving or deleting a component takes its tests with it.

Server Components as an architectural boundary

In the Next.js App Router, the split between server and client is not just a rendering detail. It is the most important boundary in the app, and you should place it on purpose. The Next.js lesson on Server and Client Components covers the mechanics. Here is the architecture.

Server Components run only on the server. They can read the database, call internal services and use secrets, and none of that code ships to the browser. Client Components (files marked "use client", and everything they import) ship JavaScript and can use state, effects and event handlers. The goal is a mostly-server tree with small client islands where interaction is needed.

An orders page with client islands
app/orders/page.tsxserver: awaits getOrders(filters)OrdersHeaderserver: static markup, zero JSOrderFiltersclient island: reads and updates the URLRefundButtonclient island: click calls a server actionOrderRowserverOrdersTableserver: rows rendered to HTMLPaginationserver: plain links with search paramsroot

The page is a server component. It parses searchParams, calls the feature's server-only data function, and gets plain objects back.

1/4

Three rules turn this into an architecture rather than a pile of files:

  1. One server-only data layer per feature. Put database and internal API calls in a module like features/orders/data.ts and start it with import "server-only". If a client component ever imports it, directly or through a chain of imports, the build fails instead of shipping your database code or a secret to the browser. The Next.js docs recommend this kind of data access layer.
  2. The data layer checks authorization and returns DTOs. Do the "may this user see these orders?" check inside the data function, not in the page, so every caller gets it. Return only the fields the UI needs. Anything you pass as a prop to a client component ends up in the HTML sent to the browser, so a full user record with an isAdmin flag or an internal note is a leak waiting to happen.
  3. Server Actions are public endpoints. A function marked "use server" can be called with a plain HTTP request by anyone who finds it, not only by your button. Validate the input and check the session inside every action, exactly as you would in an API route.
features/orders/data.ts
import "server-only";
import { db } from "@/lib/db";
import { requireUser } from "@/lib/auth";
import type { OrderSummary } from "./types";
 
export async function getOrders(filters: Filters): Promise<OrderSummary[]> {
  const user = await requireUser();                 // authorization lives here
  const rows = await db.order.findMany({ where: { customerId: user.id, ...toWhere(filters) } });
  return rows.map((r) => ({ id: r.id, status: r.status, totalCents: r.totalCents })); // DTO
}

With this in place, client-side data fetching (TanStack Query) is for the parts that are truly interactive after load, such as live search, infinite scroll or polling. The first render's data comes from the server.

Quick check
What does adding import "server-only" to the top of features/orders/data.ts actually protect against?
Need a nudge? A hint rules out a wrong answer.

Layering the design system

Your UI code has layers just like a backend, and the same rule applies: dependencies point one way. A useful split, from the bottom up:

UI layers, imports point down only
  1. Routes / pagescompose features for one URL, no logic of their own
  2. Features and widgetsCheckoutForm, OrdersTable with filters: data, state, use cases
  3. Domain componentsOrderStatusBadge, PriceTag, CustomerAvatar: know business types
  4. UI componentsButton, Dialog, DataTable: styled, no business words
  5. Primitivesheadless behaviour from Base UI, Radix or React Aria: focus, keyboard, ARIA
  6. Tokenscolours, spacing, type scale as CSS variables

Tokens and primitives are the foundation. Primitives give you accessible behaviour (focus traps, arrow-key navigation) without any look.

1/5

The simplest test: if a file in components/ui imports anything from features/ or mentions a business word like order, a layer has leaked. Generic components that know the domain cannot be reused, and domain rules hidden in a button are hard to find.

Feature-Sliced Design (FSD) is a published convention that names these layers so teams do not have to invent them. From top to bottom its layers are app, pages, widgets, features, entities and shared. A module may import only from layers below it, and slices on the same layer (two features, say) may not import each other. Each slice exposes a public API through an index.ts, and inside it code is grouped into segments such as ui, model and api. You do not have to adopt FSD to use its ideas, and its folder names clash with Next.js's own app and pages folders, so check the FSD docs for its Next.js guidance if you do.

Whatever you choose, enforce it with a tool, not a wiki page. ESLint's no-restricted-imports or eslint-plugin-boundaries can fail CI when components/ui imports from features, and FSD has its own linter. Rules that live only in a document drift within a quarter.

Match the pairs0/4 matched

Which Feature-Sliced Design layer fits each piece of code?

Choose an item, then its match on the other side.

Error and Suspense boundaries are layout decisions

You met error boundaries and Suspense as mechanisms in the Data Fetching lesson. At the architecture level, the question is where to put them, because their placement decides what users see when something is slow or broken.

A boundary catches everything below it. Put one error boundary at the root and a failing recommendations widget blanks the whole checkout. Put one around every component and the page loads as a dozen spinners that pop in at random, shifting the layout as they go. The right answer sits in between, and it follows the shape of the page:

  • One error boundary per independent region. If the region can fail without stopping the user's task (recommendations, reviews, a sidebar), wrap it so it fails alone, with a fallback and a retry.
  • Group what should appear together. Things a user reads as one unit (an order's header and its line items) belong in one Suspense boundary, so they appear at once instead of in pieces.
  • Make fallbacks the same size as the content. A skeleton that matches the final layout prevents the jump that hurts Cumulative Layout Shift.
  • Keep the critical path outside optional boundaries. The pay button should never wait for a slow recommendations query.
React
import { Component, useState } from "react"; class ErrorBoundary extends Component<{ fallback: React.ReactNode; children: React.ReactNode }, { failed: boolean }> { state = { failed: false }; static getDerivedStateFromError() { return { failed: true }; } componentDidCatch(error: Error) { console.error("report to monitoring:", error.message); } render() { return this.state.failed ? this.props.fallback : this.props.children; }} function Recommendations({ broken }: { broken: boolean }) { if (broken) throw new Error("recommendations API returned 500"); return <p style={{ margin: 0 }}>You might also like: Cap, Bag</p>;} export default function App() { const [broken, setBroken] = useState(false); const [attempt, setAttempt] = useState(0); const retry = () => { setBroken(false); setAttempt((n) => n + 1); }; return ( <div style={{ fontFamily: "system-ui", display: "grid", gap: 8, maxWidth: 360 }}> <h3 style={{ margin: 0 }}>Checkout</h3> <p style={{ margin: 0 }}>Mug x1, total $12.00</p> <button onClick={() => setBroken(true)}>Break recommendations</button> <ErrorBoundary key={attempt} fallback={<p style={{ margin: 0 }}>Recommendations unavailable. <button onClick={retry}>Retry</button></p>} > <Recommendations broken={broken} /> </ErrorBoundary> <button>Pay now</button> </div> );}

Break the widget and the checkout, total and pay button stay. Changing the boundary's key is what resets it for the retry.

Next.js turns these decisions into files. A loading.tsx in a route segment wraps that segment's page in a Suspense boundary, and an error.tsx (which must be a client component) wraps it in an error boundary with a way to retry. An error.tsx does not catch errors thrown by the layout.tsx in the same segment, because the layout sits above it. Those go to the parent segment's error file, and errors in the root layout need global-error.tsx. Inside a page you still add your own <Suspense> and error boundaries around slow or optional widgets.

Remember what error boundaries do not catch: errors in event handlers, errors in setTimeout callbacks or other async code outside rendering, and errors thrown by the boundary component itself. A failed onClick mutation needs its own error state (TanStack Query's isError on the mutation, or a try/catch that sets state).

Quick check
A product page has one Suspense boundary at the root. The reviews query sometimes takes 4 seconds, and the whole page, including the 'Add to cart' button, waits for it. What is the best change?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

Compound Accordion

Finish a compound component Accordion with parts Accordion.Item, Accordion.Trigger and Accordion.Panel. The App that uses it is already written; do not change it.

  • every panel starts closed (not rendered)
  • clicking a trigger opens its item's panel
  • only one item is open at a time: opening another closes the first
  • clicking the trigger of the open item closes it
  • each trigger is a <button> with aria-expanded set to true or false

Share the open item through context from Accordion, and let each Item tell its Trigger and Panel which value they belong to (a second context works well).

React
import { createContext, useContext, useState } from "react"; // Hint: one context for "which item is open", one for "which item am I in". function Accordion({ children }: { children: React.ReactNode }) { return <div>{children}</div>;} function Item({ value, children }: { value: string; children: React.ReactNode }) { return <div>{children}</div>;} function Trigger({ children }: { children: React.ReactNode }) { return <button>{children}</button>;} function Panel({ children }: { children: React.ReactNode }) { return <div>{children}</div>;} Accordion.Item = Item;Accordion.Trigger = Trigger;Accordion.Panel = Panel; export default function App() { return ( <Accordion> <Accordion.Item value="shipping"> <Accordion.Trigger>Shipping</Accordion.Trigger> <Accordion.Panel>Orders ship within 2 business days.</Accordion.Panel> </Accordion.Item> <Accordion.Item value="returns"> <Accordion.Trigger>Returns</Accordion.Trigger> <Accordion.Panel>Return anything within 30 days.</Accordion.Panel> </Accordion.Item> <Accordion.Item value="payments"> <Accordion.Trigger>Payments</Accordion.Trigger> <Accordion.Panel>We accept cards and PayPal.</Accordion.Panel> </Accordion.Item> </Accordion> );}
Key terms
feature-based structure
Organising code by feature (checkout, orders) so everything that changes together lives together.
custom hook
A function starting with use that holds state and logic so components can stay mostly markup.
compound component
A family of components (Tabs.List, Tabs.Tab, Tabs.Panel) that share state through context.
render prop
A prop that is a function returning UI, used to share logic before hooks.
server cache
A library like TanStack Query that fetches, caches and refetches server data, so it is not hand-copied into client state.
colocation
Keeping related files, like a component and its test, in the same folder.
server state
A cached copy of data owned by a server, which can go stale and needs refetching and invalidation.
query key factory
One module that builds every cache key for a feature, so invalidation is consistent and keys are never typed by hand.
client island
A small client component inside a mostly server-rendered tree, used only where interaction is needed.
server-only
A package whose import makes the build fail if a client component pulls the module into the browser bundle.
Feature-Sliced Design
A published convention that organises frontend code into layers (app, pages, widgets, features, entities, shared) with one-way imports.