Catalogue / react-interface-patterns
react-interface-patterns
Older skill: source not recordedSignedGuides React and Next.js interface work: choosing component composition, custom hooks, state ownership, data fetching, forms, performance optimization, error boundaries, motion, and accessibility patterns based on the app's actual contracts. Use when the user asks to "build a React component", "mana…--- name: react-interface-patterns description: >- Guides React and Next.js interface work: choosing component composition, custom hooks, state ownership, data fetching, forms, performance optimization, error boundaries, motion, and accessibility patterns based on the app's actual contracts. Use when the user asks to "build a React component", "manage state in this app", "fix slow renders", "wire up this form with validation", or "make this modal accessible". Not for non-React frameworks, backend API design, or unmeasured speculative optimization. ---
Select a pattern from the interface contract
Before choosing patterns, read the room:
- Installed framework and library versions, and the app vs pages router.
- Neighboring components, routing conventions, design tokens, API types, tests.
- The client/server boundary for each piece of data.
Then define the user action, the loading/error/empty/success states, and observable acceptance criteria before touching code.
Confirmation
Ask before: editing or creating files, changing dependencies or configuration, running artifact-writing tools, starting servers, making network requests, submitting forms, or publishing. Show paths, commands, and side effects. Approval to inspect is not approval to mutate; use synthetic local fixtures until external behavior is approved.
Never
Never mutate props or existing state, memoize to conceal a correctness bug, expose server secrets in client bundles, use a placeholder as the sole accessible label, ship an unfocused or untrapped modal, treat an incomplete keyboard handler as an accessible combobox, print sensitive exception messages, silently discard request races, or claim unexecuted checks passed. Never introduce a helper import without providing or locating its implementation.
Match structure and state to responsibility
Prefer composition with typed children and a small explicit variant API over inheritance. Shared card/header/body primitives express structure without forcing one layout on every consumer.
- Compound controls can share a guarded context; throw a useful development
error when a child renders outside its provider.
- For tabs, build complete tablist/tab/tabpanel relationships with selected
state, roving focus, and keyboard behavior — not just a class swap.
- Decide controlled versus default-value behavior explicitly.
- A render-prop loader separates acquisition from presentation and must
expose loading, error, and nullable data honestly.
- Custom hooks isolate reusable transitions: a functional-update toggle, a
debounce timer with cleanup.
- Keep local state local; a reducer handles coupled transitions; context
shares within a subtree.
- Zustand fits cross-component client state when ownership and selectors are
clear. Do not stuff remote server state into bespoke context just to dodge a cache library.
Reducers return new objects and arrays, use discriminated actions, preserve unaffected values, and define initial state. Guard consumers against a missing provider; split context or add selectors if unrelated consumers rerender. Store an entity ID rather than a stale copy so selection tracks updated records.
Make data ownership explicit
For SWR or TanStack Query, define against the installed API:
- Stable keys (including request identity), enabled conditions, stale/cache
policy, invalidation, retry/backoff, cancellation, success/error behavior.
- A naive effect refetches forever if given a freshly created fetcher or
options object each render — stabilize dependencies deliberately.
- Check HTTP status and validate runtime payloads before assigning generic
TypeScript types; handle stale responses and unmount cleanup.
- Distinguish callback failures from network failures; label them accurately.
In Next.js, check which router the route uses. Server components fetch close to the data source; interactive hooks need a client boundary. Keep server credentials and authorization on the server. Define serializable props, caching/revalidation, and route loading/error behavior for the installed version. Prevent request waterfalls and hydration mismatches. For client routing, verify navigation semantics, back/forward, query parameters, focus, and accessible links — a clickable div is not a route.
Complete original cancellable fetch helper
This framework-independent helper can be called from a hook, render-prop loader, or test. Its fetchImpl argument enables offline tests. Every caller must supply a runtime validator for its actual contract.
async function loadJson(url, validate, signal, fetchImpl = fetch) {
if (typeof validate !== 'function') throw new TypeError('A validator is required');
const response = await fetchImpl(url, { signal, headers: { accept: 'application/json' } });
if (!response.ok) throw new Error(`Request failed with status ${response.status}`);
const payload = await response.json();
if (!validate(payload)) throw new TypeError('Unexpected response shape');
return payload;
}
function isWorkshopList(value) {
return Array.isArray(value) && value.every(item =>
item !== null && typeof item === 'object' &&
typeof item.id === 'string' && typeof item.title === 'string');
}A complete React hook wrapping that helper follows. Put the helper definitions above it in the same module; the only import is installed React. It handles URL changes, aborts, and a reload trigger. Consumers must authorize any actual service request.
import { useEffect, useReducer, useState } from 'react';
type Workshop = { id: string; title: string };
type Result =
| { phase: 'loading'; data: null; message: null }
| { phase: 'ready'; data: Workshop[]; message: null }
| { phase: 'error'; data: null; message: string };
export function useWorkshops(url: string) {
const [revision, reload] = useReducer((value: number) => value + 1, 0);
const [result, setResult] = useState<Result>({ phase: 'loading', data: null, message: null });
useEffect(() => {
const controller = new AbortController();
let active = true;
setResult({ phase: 'loading', data: null, message: null });
loadJson(url, isWorkshopList, controller.signal).then(data => {
if (active) setResult({ phase: 'ready', data: data as Workshop[], message: null });
}).catch(() => {
if (active) setResult({ phase: 'error', data: null, message: 'Workshops could not be loaded.' });
});
return () => { active = false; controller.abort(); };
}, [url, revision]);
return { ...result, reload };
}When moving the JavaScript helper into a TypeScript module, add explicit URL, signal, fetch, and validator typings to the project's strictness level — the mixed-language sketch above is not a complete strict module. Prefer a cache-backed query library when deduplication, persistence, or mutation invalidation matters. A debounce hook must cancel its prior timer, depend on value and delay, and drop obsolete searches via cancellation or request identity.
Measure before optimizing
Profile the representative interaction, render counts, bundle size, and long-list behavior first. Then:
useMemofor measured costly pure derivations.useCallbackwhere stable function identity actually helps a consumer.React.memofor suitable pure components.- Copy before sorting:
[...items].sort(...)keeps the input intact.
Memoization is an optimization, not a semantic guarantee; keep dependency arrays correct.
Use lazy plus Suspense for heavy optional modules with real exported components and meaningful fallbacks. Handle chunk-load failures separately, and verify server-rendering behavior for the installed version. Split at useful route or feature boundaries, not for every decoration.
A virtualizer such as @tanstack/react-virtual needs a scroll element, row count, estimated size, overscan, a total-height spacer, measured variable rows where needed, and stable item keys. Position visible rows from their virtual start and keep real data identity. Verify keyboard focus, screen-reader expectations, scroll restoration, and dynamic heights — virtualization can drop the focused item. Skip it when a short list suffices.
Make forms complete
Forms need a defined model and a per-field error map:
- Controlled inputs use immutable functional updates, explicit labels,
matching IDs, and error association via aria-describedby/aria-invalid.
- Validate required trimmed values, real length limits, date parseability,
and domain constraints; Zod schemas are fine, but server-side validation and authorization remain mandatory.
- Avoid naming a model
FormDatawhere it shadows the browser built-in.
On submit: prevent native navigation only when appropriate, validate, set pending state, suppress duplicate submission, run only the approved mutation, and give visible accessible success/error feedback. Keep server errors distinct from field errors and preserve user input. Give buttons an explicit type. Implement every displayed field and callback — a comment promising omitted fields is not a working form.
Handle failures and motion accessibly
An error boundary catches rendering and lifecycle failures in its descendant subtree — not event-handler exceptions or arbitrary async work. Implement getDerivedStateFromError, log safely via componentDidCatch, and show a generic message. Reset through a meaningful retry or key change and clear stored error state. Never retry a deterministic crash blindly or print stack traces to users.
With the installed Framer Motion version, motion and AnimatePresence animate keyed list entry/exit and modal transitions. Keep keys stable, use approved tokens and durations, honor reduced motion, and avoid layout shift. Presence animation supplies neither modal semantics nor focus management.
Prefer a tested dialog primitive or the native dialog. On open: save prior focus, focus the initial control, trap or contain focus, make background content inert as appropriate, label the dialog, handle Escape, and restore focus on close or unmount. Closing the overlay must not swallow workflow state. Use role="dialog" and aria-modal only when modal behavior is real.
For a custom combobox or listbox, define focusability, expanded state, controlled popup ID, active descendant and selection, labels, and options. Support ArrowUp/ArrowDown, Enter, Escape, and appropriate Home/End/typeahead; handle zero and disabled options safely. An ARIA role on a nonfocusable div with an index counter is not a combobox. Verify with keyboard and assistive technology.
Verify and hand off
Test, using installed tools: reducer transitions; hook loading, error, cancellation, and refetch; runtime validation; empty results; duplicate submits; routing; chunk failure; keyboard focus; reduced motion; mobile layout; and measured performance deltas. State which examples ran as pure offline helpers and which need framework or browser integration. Hand off changed files, decisions, measurements, real tests, missing dependencies, unresolved behavior, and approved release/rollback steps.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 11.2 kB | a772d7b30ad6 |
| examples.json | 1.7 kB | 12ca52d6be80 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.1 Current | Not recorded | 6 Oct 2026 | |
| 1.0.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.