Frontend design patterns: Which to use and when

Contents
Frontend design patterns fall into two groups: code patterns that organize logic and state, and UI patterns that organize interaction. Most of the classic Gang of Four catalogue survives only as language features: ES modules, hooks and store subscriptions.
The patterns that carry weight today are composition, state placement, rendering strategy and the keyboard contract for interactive widgets. Which ones you need depends on how many consumers share a piece of logic, how fresh your data must be and how interactive the page is.
What are frontend design patterns?
Frontend design patterns are named, reusable approaches to recurring problems in client-side code, and the term covers two different things. Code patterns structure components, state and rendering, such as compound components, custom hooks and islands architecture in React and beyond. UI patterns settle recurring interface problems, such as dialogs, theming and responsive components.
Reach for a code pattern when duplicated logic or tangled state slows every change. Reach for a UI pattern when users hit the same interaction problem on several screens. Netguru builds web applications and design systems for enterprise clients, with React and TypeScript front ends.
We recommend starting with custom hooks and deliberate state placement, because they remove the most duplication for the least added abstraction. A short-lived app with a handful of screens rarely needs more than plain components.
Pattern selection table: Problem, use and avoid
Choose a frontend design pattern by the problem in front of you, and read the avoid column before adopting it. Custom hooks, a server state cache, container queries, code splitting and design tokens each fix one problem and misfire outside it.
The table maps problems to patterns:
| Pattern | Problem it solves | Use when | Avoid when |
|---|---|---|---|
| Custom hooks | Stateful logic duplicated across components | Two or more components share the same state or effect logic | The hook wraps one useState call, or the logic needs no React state and a plain function works |
| Compound components | Related parts (tabs, accordion, menu) that share implicit state but need flexible markup | Consumers must reorder or restyle the parts | The structure is fixed and props already express it |
| Lifted state and context | Siblings that must stay in sync; values read deep in the tree | Lift for nearby siblings; use context for slow-changing values such as theme or locale | Context holds fast-changing state, because every consumer re-renders on each change |
| Server state cache | Fetched data that needs deduplication, revalidation and invalidation | Many components read the same remote data | The state is local UI state, or the data is fetched once during server render |
| Design tokens with CSS custom properties | Hard-coded colors and spacing that block theming | You need multiple themes or brands, or shared values across components | A single throwaway prototype where the indirection costs more than it saves |
| Container queries | A component that must adapt to the space it is given | The same card renders in a sidebar and a main column | The change is page-level layout tied to the viewport |
| Code splitting | Large bundles delaying first interaction | Routes or heavy widgets (editors, charts) load on demand | The component is above the fold, where a lazy chunk adds a request waterfall |
| Islands architecture | Mostly static pages paying for full-page hydration | A few interactive regions sit in otherwise static content | Most of the page is stateful, as in a dashboard shell |
| WAI-ARIA Authoring Practices patterns | Custom widgets without keyboard or screen reader support | You build a dialog, tabs or combobox from scratch | A native element (dialog, select) already covers the case |
| Render props and higher-order components | Logic reuse in class-era code | You maintain code that already uses them | You write new code; custom hooks cover most of these cases |
Theme switching shows how two rows combine. Define tokens as custom properties on :root, then override them under a theme class or a prefers-color-scheme media query, so components never reference raw values.
The table is our judgment, and team size shifts it. A three-person team often needs only lifted state and a server state cache, while a multi-team product gains most from tokens and shared compound components.
Naming the pattern in code review also gives the team a shared vocabulary for UI discussions.
Which React design patterns still matter?
In React, composition, compound components and custom hooks still earn their place, while higher-order components and render props are legacy patterns for sharing logic. Choose among the three that remain by asking who owns the markup and who owns the logic.
The ownership rule:
| Who owns the markup | Who owns the logic | Pattern |
|---|---|---|
| The caller | Nobody, the component only lays things out | Composition with children or slot props |
| The caller, arranging parts freely | The component, shared across its parts | Compound components |
| The caller | The caller, reused across components | Custom hook |
| The component | The component | Plain component with props |
Compound components fit widgets whose parts must coordinate, such as tabs, accordions and menus. The parent holds the state and exposes it to its children through context, and the caller decides the order and wrapping of the parts. patterns.dev documents the pattern. If callers never rearrange the parts, a plain props API is simpler and avoids the context layer.
Custom hooks cover the case where logic repeats but markup differs. The Custom hooks describes them as sharing stateful logic, not state itself, so each caller gets an independent copy. For worked examples, see our React hooks examples.
Higher-order components and render props solved logic reuse before hooks existed. Both add wrapper nesting and obscure where a prop comes from. Two uses remain defensible: error boundaries, which react.dev still documents as class components, and render callbacks that receive per-item data, such as a list row renderer. The second is our judgment, not a rule.
A migration that does not break callers has three steps:
- Extract the logic into a custom hook that returns the same values the render prop passed to its child.
- Rewrite the HOC or render prop component as a thin wrapper around that hook.
- Move callers to the hook one at a time, then delete the wrapper when nothing references it.
function useWindowWidth(): number {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return width;
}
// Legacy wrapper, kept only while callers migrate
function withWindowWidth<P extends { width: number }>(Wrapped: ComponentType<P>) {
return function WithWindowWidth(props: Omit<P, "width">) {
const width = useWindowWidth();
return <Wrapped {...(props as P)} width={width} />;
};
}
The wrapper keeps old call sites compiling while new code calls the hook directly. Once the last caller moves, deleting withWindowWidth is a one-file change.
Compound components and where they break
Compound components break when the parent injects props into its direct children with cloneElement, because wrapping a child in any other element cuts the link. React Context removes that dependency on tree shape.
The cloning version works until someone adds a wrapper:
function Tabs({ children }: { children: React.ReactNode }) {
const [active, setActive] = useState(0);
return React.Children.map(children, (child, index) =>
React.cloneElement(child as React.ReactElement<TabProps>, {
selected: index === active,
onSelect: () => setActive(index),
}),
);
}
// Billing is wrapped, so it never receives selected or onSelect
<Tabs>
<Tab label="Overview" />
<div className="tab-slot"><Tab label="Billing" /></div>
</Tabs>
The injected props land on the div. The Billing tab renders unselected and ignores clicks, with no runtime error and no type error, since cloneElement is loosely typed. A fragment wrapper fails the same way, because Children.map does not traverse into fragments.
The fix is to publish state through context and let each sub-component read it:
const TabsContext = createContext<TabsState | null>(null);
function useTabs() {
const ctx = useContext(TabsContext);
if (!ctx) throw new Error("Tab must render inside Tabs");
return ctx;
}
Tab takes a value prop instead of relying on its index, and finds the shared state at any depth.
The cost is that every consumer re-renders when the context value changes. For a tab strip that is fine. For a large data grid, we recommend splitting state and dispatch into two contexts.
Container and presentational components vs hooks
Custom hooks replaced most container components by moving state and data fetching into a function that any presentational component can call, which removes the wrapper layer. The presentational half survives unchanged.
A container like this mixes fetching with rendering:
function UserCardContainer({ id }: { id: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
fetchUser(id).then(setUser);
}, [id]);
return user ? <UserCard user={user} /> : <Spinner />;
}
The migration to custom hooks takes four steps:
- Confirm UserCard takes only props and touches no data source. Leave it alone.
- Move the state and effect into
useUser(id)and return what the container passed down. - Call the hook where the container was rendered, and delete the container.
- Replace any higher-order components or render props that only injected that data.
function useUser(id: string) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
fetchUser(id).then(setUser);
}, [id]);
return user;
}
function UserScreen({ id }: { id: string }) {
const user = useUser(id);
return user ? <UserCard user={user} /> : <Spinner />;
}
The hook is now the single place to fix the race when id changes, or to swap the effect for a server state cache. Render props and higher-order components still work, but they add nesting that a hook avoids.
JavaScript design patterns examples for frontend
Observer, Module, Singleton, Factory and Decorator still shape frontend code, mostly as store subscriptions, ES modules, plain functions and wrappers. The pattern names matter less than the primitive that now does the job.
The mapping side by side:
| Classic pattern | Modern frontend form | Typical example | Watch for |
|---|---|---|---|
| Observer | Store subscription, signals | useSyncExternalStore, Solid or Preact signals | Leaked subscriptions, mutated state that never notifies |
| Module | ES module | One file, explicit exports | Side effects at import time |
| Singleton | Module-scope instance | export const cartStore | Shared state across server requests |
| Factory | Function returning an object | createStore, createClient | Factories that grow flag arguments |
| Decorator | Wrapper function or component | withRetry, a higher-order component | Stacked wrappers that hide the call path |
One small store covers four of the five rows:
type Listener = () => void;
function createStore<T>(initial: T) {
let state = initial;
const listeners = new Set<Listener>();
return {
get: () => state,
set(next: T) {
state = next;
listeners.forEach((notify) => notify());
},
subscribe(listener: Listener) {
listeners.add(listener);
return () => { listeners.delete(listener); };
},
};
}
// cart.ts: the module cache gives one instance per bundle
export const cartStore = createStore<string[]>([]);
createStore is the Factory, subscribe is the Observer, and the ES module is both the Module and the Singleton, because the module system evaluates the file once. A React component reads it with useSyncExternalStore(cartStore.subscribe, cartStore.get), which is the documented hook for external stores. Always replace state with a new value, since the hook compares by reference.
Signals are Observer with automatic dependency tracking. Solid, Preact and Angular ship them, and React does not, so in React the subscription route above is the one to use.
The Decorator is the easiest to write as a function wrapper:
function withRetry<A extends unknown[], R>(
fn: (...args: A) => Promise<R>,
tries = 3,
) {
return async (...args: A): Promise<R> => {
for (let attempt = 1; ; attempt++) {
try {
return await fn(...args);
} catch (error) {
if (attempt >= tries) throw error;
}
}
};
}
For components, the same idea is the higher-order component, which custom hooks have largely displaced.
Two caveats apply. A module-scope Singleton is shared by every request when the module runs on a server, so per-user data in it can leak between users. On the server, create the store per request and pass it down through context.
Also, a store is often more than you need. If two sibling components share a value, lifting state to their common parent is simpler and easier to test, and the store can wait until prop passing becomes the problem.
Where should state live?
State should live in the lowest component that needs it and move up only when a specific trigger fires. Our recommended order, a judgment call and not a standard, starts with one classification step and then climbs five rungs.
Step zero: classify the data. Anything fetched from an API is a copy of someone else's data. It belongs in a server state cache (cache keys, stale-while-revalidate, request deduplication), not in useState. react.dev cautions against fetching in Effects and points to framework data loading or a client-side cache. Only client-owned state enters the ladder.
- Local state. Keep it in the component that renders it. Move up the moment a sibling needs to read or change the same value.
- Lifted state. Move the value to the closest common parent and pass it down with props, as react.dev describes for sharing state. Move up when props pass through three or more layers that don't use them.
- React Context. Use it for values that change rarely and are read widely: theme, locale, the current user. The trigger to leave is re-rendering. React re-renders every component that reads a context when its value changes, so a frequently updated value in one context re-renders all of its consumers.
- External store. Use a store read through useSyncExternalStore or a selector-based library when many distant components read slices of fast-changing state, such as a canvas, a cart or a filter panel. Selectors limit re-renders to components whose slice changed.
- Signals. Preact, Solid and Angular ship signals, which track dependencies at the value level and update only the DOM nodes that read them. React has no built-in signals, so in React rung 4 fills this role. A TC39 proposal aims to add signals to JavaScript itself.
A minimal split keeps rung 3 cheap by separating the value from its setter:
const ThemeValue = createContext<Theme>("light");
const ThemeSetter = createContext<(t: Theme) => void>(() => {});
Components that only call the setter no longer re-render when the value changes.
The ladder has limits. Form state with many fields often stays local on purpose, because lifting it re-renders the whole form on every keystroke. URL state (filters, pagination, selected tab) belongs in the router, where links and the back button can reach it. A profiler measurement, not a guess, should justify any move to rung 4 or 5.
Which rendering pattern fits your page?
Pick the rendering pattern from two inputs: how fresh the data must be when the request arrives, and how much of the page responds to input. Everything else is a tiebreaker. Your framework decides which of these you can use without extra setup: Next.js and similar frameworks support server and static rendering, while a plain client-side React app does not.
The mapping below is our judgment, not a standard, with the cost each choice carries:
| Pattern | Fits when | Cost to watch |
|---|---|---|
| Static generation | Content changes on deploy or on a revalidation schedule; light interactivity | Build time grows with page count; stale until rebuilt |
| Server-side rendering | Data differs per request or per user and the first paint must contain it | Server load per request; hydration cost; mismatch risk |
| Streaming server-side rendering | One slow data source should not block the rest of the page | Status code and headers are sent before late errors surface |
| Islands architecture | Mostly static content with a few interactive widgets | No shared component tree between islands |
| Client-side rendering | Authenticated dashboards where search indexing is irrelevant | Blank shell until JavaScript runs; needs code splitting |
Streaming server-side rendering flushes the page shell first and fills Suspense boundaries as slow queries resolve. Because the response has already started, a failure in a late boundary can't change the HTTP status, so put the data that decides 404 or redirect outside the streamed part. web.dev's rendering overview covers the same spectrum in more depth.
Any pattern that ships server HTML and then hydrates can produce a hydration mismatch: the server markup differs from the first client render. Common sources are the current time, a time zone or locale format, and random IDs. Render a stable value first and localize after mount.
function PublishedAt({ iso }: { iso: string }) {
const [label, setLabel] = useState(iso.slice(0, 10));
useEffect(() => {
setLabel(new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" }));
}, [iso]);
return <time dateTime={iso}>{label}</time>;
}
Islands architecture hydrates each interactive widget independently and leaves surrounding HTML inert. Since islands don't share a component tree, context can't carry state between them. A cart badge and an add-to-cart button in separate islands need an external store module that both import.
Static generation with islands is our default for content-heavy pages. Move to server-side rendering only when the first paint must contain per-request data.
Web design patterns for theming and responsive components
Design tokens, CSS custom properties and container queries cover theming and component-level responsiveness without a runtime styling library. Tokens hold the decisions, custom properties carry them to the browser, and container queries let each component respond to its own width.
Split tokens into two layers. Primitive tokens name raw values (--color-gray-900). Semantic tokens name roles (--surface-default) and point at primitives. Components read only semantic tokens, so dark mode redefines the semantic layer in one place.
:root {
--color-gray-50: #f8fafc;
--color-gray-900: #0f172a;
--accent-hue: 220;
--surface-default: var(--color-gray-50);
--text-default: var(--color-gray-900);
--accent: hsl(var(--accent-hue) 80% 45%);
}
:root[data-theme="dark"] {
--surface-default: var(--color-gray-900);
--text-default: var(--color-gray-50);
}
.card {
background: var(--surface-default);
color: var(--text-default);
border-inline-start: 4px solid var(--accent);
}
We recommend an explicit data-theme attribute over prefers-color-scheme alone, with the media query used only to choose the initial value. That way a stored user choice always wins. Set the attribute before first paint to avoid a flash of the wrong theme.
Runtime changes go through setProperty, which keeps styling out of inline style objects and avoids a re-render.
export function setTheme(root: HTMLElement, theme: "light" | "dark"): void {
root.dataset.theme = theme;
}
export function setAccentHue(el: HTMLElement, hue: number): void {
el.style.setProperty("--accent-hue", String(hue));
}
Container queries handle the layout side. The wrapper becomes the query container, and the component changes shape based on the space it is given, not the viewport.
.card-host {
container-type: inline-size;
}
.card {
display: block;
}
@container (min-width: 32rem) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}
The fallback is the base rule. A browser that ignores @container renders the single-column card, which is a usable layout. Check the browser compatibility table on Container queries against your Baseline target before removing that default.
Two limits apply. container-type: inline-size applies layout containment, so the host cannot take its inline size from its children. A component cannot query the container it is itself the root of, which means the wrapper element is required. Governing token names across several teams is a separate problem, covered in design system patterns.
Accessible dialogs, tabs and comboboxes
The WAI-ARIA Authoring Practices define a keyboard and focus contract for each of these widgets, and most accessibility bugs break that contract instead of omitting an attribute.
The first rule of ARIA use in the W3C note Using ARIA says the same: when a native HTML element or attribute already has the semantics and behavior you need, use it instead of adding ARIA to another element.
The contracts and their usual failures, side by side:
| Pattern | Contract | Typical failure |
|---|---|---|
| Dialog | Focus moves in on open, stays inside, returns to the invoker on close; Escape closes | Focus drops to the document body after close |
| Tabs | One tab stop for the tablist; arrow keys move between tabs; Tab enters the panel | Every tab has tabindex="0", so Tab cycles through all of them |
| Combobox | DOM focus stays in the input; aria-activedescendant names the active option | Focus moves into the listbox and typing stops working |
| Disclosure | A button with aria-expanded and aria-controls toggles the content | Content hidden with CSS while the attribute never changes |
Dialogs: Use the native element
The native dialog element opened with showModal() makes the rest of the page inert, closes on Escape, and restores focus to the previously focused element. A custom div with role="dialog" has to rebuild all three.
If you must build one, save document.activeElement before opening and call focus() on it in every close path, including backdrop clicks. The APG modal dialog pattern lists the full keyboard behavior.
Tabs: Roving tabindex
In the APG tabs pattern, only the selected tab has tabindex="0" and the others have -1. Arrow keys move that single tab stop, which is the technique the APG calls roving tabindex.
function moveTabFocus(tabs: HTMLElement[], current: number, key: string): void {
const last = tabs.length - 1;
const next =
key === "ArrowRight" ? (current === last ? 0 : current + 1)
: key === "ArrowLeft" ? (current === 0 ? last : current - 1)
: key === "Home" ? 0
: key === "End" ? last
: current;
tabs[current].tabIndex = -1;
tabs[next].tabIndex = 0;
tabs[next].focus();
}
In React, we recommend keeping the focused index in the parent of a compound component, so individual tab children never manage tabIndex themselves.
Comboboxes and disclosure
The APG combobox pattern keeps DOM focus in the input and points aria-activedescendant at the highlighted option. Mirror the popup state in aria-expanded on the input.
The same attribute drives a disclosure. Collapsed content hidden with display: none also disappears from find-in-page and from screen reader navigation until a user expands it, so keep important answers outside collapsed regions. The hidden="until-found" value addresses find-in-page, but check its Baseline status before relying on it.
Performance patterns: Code splitting, virtualization and tree shaking
Code splitting in React defers route and widget bundles until they are needed, virtualization mounts only the visible rows of a list, and tree shaking drops unused exports at build time. Each pattern has a failure mode that can cost more than it saves.
Code splitting. Put a dynamic `import()` behind React.lazy and Suspense, as web.dev's code-splitting guide describes. Use it at route boundaries and for heavy, rarely shown widgets such as editors, charts and modals.
The failure mode is a request waterfall. The route chunk arrives, the component mounts, it fetches data, and a nested lazy child then requests its own chunk, each step waiting on the one before. Start the chunk import and the data request together in the route loader, and preload on intent:
const loadSettings = () => import("./routes/Settings");
const Settings = lazy(loadSettings);
<a href="/settings" onPointerEnter={loadSettings} onFocus={loadSettings}>
Settings
</a>
Splitting every component produces many small chunks and more round trips. We recommend a handful of deliberate split points over blanket lazy loading.
Virtualization. A virtualized list keeps only the rows in and near the viewport in the DOM, which keeps render cost flat as the data grows (web.dev on virtualizing long lists). Because off-screen rows do not exist in the DOM, browser find-in-page cannot match them, and screen readers lose the sense of list length.
Variable row heights are the other trap. The library must estimate unmeasured rows, so the scrollbar jitters and the scroll position jumps when real heights replace the estimates. Measure rows after render, or fix the height. Expose aria-setsize and aria-posinset on rows (see the MDN ARIA attribute reference). Below a few hundred simple rows, pagination or content-visibility: auto is usually cheaper than a virtualization library.
Tree shaking. Bundlers can remove unused exports only from static ES module imports. CommonJS dependencies, barrel files that re-export modules with side effects, and a missing sideEffects field in package.json all keep dead code in the bundle. Check the bundle analyzer output after adding a dependency.
Profiling these patterns against real traces is covered in our React performance optimization guide, and teams weighing where to place split points can bring in React development support.
When is a pattern over-engineering?
A pattern is over-engineering when the indirection it adds costs more to read and change than the problem it removes. Four cases recur in React codebases, each with a visible symptom and a cheaper replacement.
The cases side by side:
| Case | Symptom | Cost | Replacement |
|---|---|---|---|
| Premature React Context | A provider wraps the app to skip two prop layers | Hidden data flow; every consumer re-renders when the value changes | Lifted state, or JSX passed as children |
| God component | One file owns fetching, validation, layout and modals | Hard to test; any edit risks unrelated behavior | Custom hooks for logic, smaller components split by responsibility |
| Global store on a small site | Form inputs and toggles live in a store | Boilerplate, plus a second copy of fetched data to keep in sync | Local state, with a server state cache for fetched data |
| Abstraction before the third use | A generic component with a growing list of boolean props | Props accumulate for cases that never arrive | Duplicate twice, then extract |
Passing props through two or three layers is easy to trace with a text search. The React docs on passing data with context advise trying props and extracted components with children first. Lifted state in the nearest common parent usually settles it. Context fits values read at many distant depths, such as theme, locale or the signed-in user.
God components usually split along the seams of their useState and useEffect calls. Moving each group into a custom hook gives the logic a name and a test, and the component keeps only rendering. If an effect copies fetched data into state, you might not need that effect: a server state cache already handles caching, deduplication and revalidation.
For abstraction, we'd suggest waiting for the third real use before extracting a shared component. Two cases rarely reveal which differences are essential, and a wrong abstraction is harder to undo than duplicated markup. Larger teams with a shared design system will move that threshold earlier, because the cost of divergence is higher there.
Frontend design patterns FAQ
What are the most common design patterns in React?
Are design patterns still relevant in modern frontend development?
What is the difference between container and presentational components and hooks?
When should I use the compound components pattern in React?
What is the difference between design patterns and architectural patterns in frontend?
Which patterns to adopt first
Adopt a server state cache first and custom hooks second; add the other frontend design patterns only when a specific symptom appears.

- Server state cache: in React, the official guidance on avoiding unnecessary Effects points to data-fetching libraries and framework caches for fetching, because hand-written effects leave race conditions and caching to you.
- Custom hooks: extract one when the same logic appears in a second component.
- Design tokens as CSS custom properties: add them when a second theme or brand arrives.
- Compound components: use them when a component collects boolean props that toggle layout.
- Code splitting: apply it after a bundle measurement shows a heavy route.
When reviewing AI-generated code, we'd check first for fetches inside effects and duplicated logic that belongs in a hook. If you want a second opinion on where your codebase sits on this order, we can scope it with you.
