{"slug":"react-patterns-3","title":"react-patterns","summary":"React 18/19 patterns including hooks discipline, server/client component boundaries, Suspense + error boundaries, form actions, data fetching, state management decision trees, and accessibility-first composition. Use when writing or reviewing React components.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:01.625161Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: react-patterns\ndescription: React 18/19 patterns including hooks discipline, server/client component boundaries, Suspense + error boundaries, form actions, data fetching, state management decision trees, and accessibility-first composition. Use when writing or reviewing React components.\nmetadata:\norigin: ECC</h2>\n<h1>React Patterns</h1>\n<p>Idiomatic React 18/19 patterns for building robust, accessible, performant component trees.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Writing or modifying React function components, custom hooks, or component trees</li>\n<li>Reviewing JSX/TSX files</li>\n<li>Designing state shape or component composition</li>\n<li>Migrating class components or older <code>forwardRef</code>/<code>useEffect</code>-heavy code</li>\n<li>Choosing between local state, lifted state, context, and external stores</li>\n<li>Working with Server Components / Client Components (Next.js App Router, RSC)</li>\n<li>Implementing forms with React 19 actions or controlled inputs</li>\n<li>Wiring data fetching with TanStack Query / SWR / RSC</li>\n</ul>\n<h2>Core Principles</h2>\n<h3>1. Render is a Pure Function of Props and State</h3>\n<pre><code>// Good: derive during render\nfunction Cart({ items }: { items: CartItem[] }) {\n  const total = items.reduce((sum, i) =&gt; sum + i.price * i.qty, 0);\n  return &lt;span&gt;{formatMoney(total)}&lt;/span&gt;;\n}\n\n// Bad: derived state stored separately\nfunction Cart({ items }: { items: CartItem[] }) {\n  const [total, setTotal] = useState(0);\n  useEffect(() =&gt; {\n    setTotal(items.reduce((sum, i) =&gt; sum + i.price * i.qty, 0));\n  }, [items]);\n  return &lt;span&gt;{formatMoney(total)}&lt;/span&gt;;\n}\n</code></pre>\n<p>Derived state in <code>useEffect</code> adds a render cycle, can desync, and obscures the data flow.</p>\n<h3>2. Side Effects Outside Render</h3>\n<p>Effects, mutations, network calls, and subscriptions live in event handlers or <code>useEffect</code> — never in the render body.</p>\n<h3>3. Composition Over Inheritance</h3>\n<p>React has no inheritance model for components. Compose with <code>children</code>, render props, or component props.</p>\n<h2>Hooks Discipline</h2>\n<p>See <a href=\"../../rules/react/hooks.md\">rules/react/hooks.md</a> for the full ruleset. Highlights:</p>\n<ul>\n<li>Top-level only, never conditional</li>\n<li>Cleanup every subscription, interval, listener</li>\n<li>Functional updater (<code>setX(prev =&gt; prev + 1)</code>) when new state depends on old</li>\n<li>Default position: do not memoize — add <code>useMemo</code>/<code>useCallback</code> only when a profiler or a dependency chain proves it matters</li>\n<li>Extract a custom hook only when the same hook sequence appears in 2+ components</li>\n</ul>\n<h2>State Location Decision Tree</h2>\n<pre><code>Used by one component?\n  -&gt; useState inside it\n\nUsed by parent + a few descendants?\n  -&gt; lift to nearest common ancestor\n\nUsed across distant branches AND low-frequency reads (theme, auth, locale)?\n  -&gt; React Context\n\nHigh-frequency updates shared across the tree?\n  -&gt; external store (Zustand, Jotai, Redux Toolkit)\n\nDerived from a server?\n  -&gt; server-state library (TanStack Query, SWR, RSC fetch)\n</code></pre>\n<p>Most pages do not need context or a global store. Resist abstraction until duplicated lifting becomes painful.</p>\n<h2>Server / Client Components (RSC)</h2>\n<pre><code>// Server Component - default, async, never ships JS for itself\nexport default async function ProductPage({ params }: { params: { id: string } }) {\n  const product = await db.product.findUnique({ where: { id: params.id } });\n  if (!product) notFound();\n  return &lt;ProductView product={product} /&gt;;\n}\n\n// Client Component - opt in with \"use client\"\n\"use client\";\nexport function AddToCartButton({ productId }: { productId: string }) {\n  const [pending, startTransition] = useTransition();\n  return (\n    &lt;button\n      disabled={pending}\n      onClick={() =&gt; startTransition(() =&gt; addToCart(productId))}\n    &gt;\n      {pending ? \"Adding...\" : \"Add to cart\"}\n    &lt;/button&gt;\n  );\n}\n</code></pre>\n<p>Boundaries:</p>\n<ul>\n<li>Server -&gt; Client: pass serializable props or <code>children</code></li>\n<li>Client -&gt; Server: invoke Server Actions via <code>&lt;form action={...}&gt;</code> or imperatively from event handlers</li>\n<li>Never <code>import</code> a Server Component from a Client Component file — compose them via <code>children</code> instead</li>\n</ul>\n<h2>Suspense + Error Boundaries</h2>\n<pre><code>&lt;ErrorBoundary fallback={&lt;ErrorView /&gt;}&gt;\n  &lt;Suspense fallback={&lt;UserSkeleton /&gt;}&gt;\n    &lt;UserDetail id={id} /&gt;\n  &lt;/Suspense&gt;\n&lt;/ErrorBoundary&gt;\n</code></pre>\n<ul>\n<li>Place Suspense boundaries close to the data, not at the route root — progressively reveal content</li>\n<li>Error Boundary remains a class API; use <code>react-error-boundary</code> for a hook-friendly wrapper</li>\n<li>A boundary catches errors thrown during render, lifecycle, and constructors of its children — NOT in event handlers or async code</li>\n</ul>\n<h2>Forms</h2>\n<h3>React 19 form actions (preferred for new code)</h3>\n<pre><code>\"use client\";\nimport { useActionState } from \"react\";\n\nconst initial = { error: null as string | null };\n\nasync function updateUserAction(_prev: typeof initial, formData: FormData) {\n  \"use server\";\n  const parsed = UserSchema.safeParse(Object.fromEntries(formData));\n  if (!parsed.success) return { error: \"Invalid input\" };\n  await db.user.update({ where: { id: parsed.data.id }, data: parsed.data });\n  return { error: null };\n}\n\nexport function UserForm() {\n  const [state, formAction, pending] = useActionState(updateUserAction, initial);\n  return (\n    &lt;form action={formAction}&gt;\n      &lt;input name=\"name\" required /&gt;\n      &lt;button type=\"submit\" disabled={pending}&gt;Save&lt;/button&gt;\n      {state.error &amp;&amp; &lt;p role=\"alert\"&gt;{state.error}&lt;/p&gt;}\n    &lt;/form&gt;\n  );\n}\n</code></pre>\n<h3>Controlled inputs</h3>\n<p>Use controlled when the value drives other UI, formats on every keystroke, or implements real-time validation.</p>\n<h3>Complex forms</h3>\n<p>For multi-step forms, dynamic field arrays, or cross-field validation: use a library (React Hook Form, TanStack Form). Roll-your-own state management for forms past trivial complexity is a maintenance trap.</p>\n<h2>Data Fetching Decision Matrix</h2>\n<table>\n<thead>\n<tr>\n<th>Need</th>\n<th>Tool</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Per-request data in Next.js App Router</td>\n<td>RSC <code>await fetch()</code></td>\n</tr>\n<tr>\n<td>Client-side cache + mutations + invalidation</td>\n<td>TanStack Query</td>\n</tr>\n<tr>\n<td>Lightweight client cache + revalidation</td>\n<td>SWR</td>\n</tr>\n<tr>\n<td>Real-time subscriptions</td>\n<td>Server-Sent Events, WebSockets, or the lib's subscription API</td>\n</tr>\n<tr>\n<td>One-off fire-and-forget</td>\n<td><code>fetch()</code> in an event handler</td>\n</tr>\n</tbody>\n</table>\n<p>Avoid <code>useEffect</code> + <code>fetch</code> for application data — race conditions, no cache, no retry, no Suspense integration.</p>\n<h2>Composition Recipes</h2>\n<h3>Slot via <code>children</code></h3>\n<pre><code>&lt;Layout&gt;\n  &lt;Header /&gt;\n  &lt;Main&gt;{content}&lt;/Main&gt;\n&lt;/Layout&gt;\n</code></pre>\n<h3>Named slots</h3>\n<pre><code>&lt;Page header={&lt;Nav /&gt;} sidebar={&lt;Filters /&gt;}&gt;\n  &lt;Results /&gt;\n&lt;/Page&gt;\n</code></pre>\n<h3>Compound components (shared state via Context)</h3>\n<pre><code>&lt;Tabs defaultValue=\"profile\"&gt;\n  &lt;Tabs.List&gt;\n    &lt;Tabs.Trigger value=\"profile\"&gt;Profile&lt;/Tabs.Trigger&gt;\n    &lt;Tabs.Trigger value=\"settings\"&gt;Settings&lt;/Tabs.Trigger&gt;\n  &lt;/Tabs.List&gt;\n  &lt;Tabs.Panel value=\"profile\"&gt;&lt;Profile /&gt;&lt;/Tabs.Panel&gt;\n  &lt;Tabs.Panel value=\"settings\"&gt;&lt;Settings /&gt;&lt;/Tabs.Panel&gt;\n&lt;/Tabs&gt;\n</code></pre>\n<h3>Render prop / function-as-child</h3>\n<p>Useful when the parent needs to pass parameters to the rendered output:</p>\n<pre><code>&lt;DataLoader id={id}&gt;\n  {({ data, isLoading }) =&gt; isLoading ? &lt;Spinner /&gt; : &lt;UserCard user={data} /&gt;}\n&lt;/DataLoader&gt;\n</code></pre>\n<p>Modern alternative: a hook (<code>useData(id)</code>) returning the same shape — usually cleaner.</p>\n<h2>Performance</h2>\n<h3>When <code>React.memo</code> Actually Helps</h3>\n<p>Wrap a component in <code>React.memo</code> only when:</p>\n<ol>\n<li>It re-renders frequently</li>\n<li>Its props are usually the same between renders</li>\n<li>Its render is measurably expensive</li>\n</ol>\n<p><code>React.memo</code> adds an equality check on every render. If props differ on most renders, the check is pure overhead.</p>\n<h3>Avoiding Render Cascades</h3>\n<ul>\n<li>Lift state down rather than up where possible</li>\n<li>Split context: one context per concern, so a change to <code>themeContext</code> does not re-render auth consumers</li>\n<li>Use <code>useSyncExternalStore</code> for external state libraries — required for safe concurrent rendering</li>\n</ul>\n<h3>Lists</h3>\n<ul>\n<li>Provide stable <code>key</code> props (database id, not array index)</li>\n<li>Virtualize long lists with <code>@tanstack/react-virtual</code> or <code>react-window</code> once visible item count exceeds ~50 with non-trivial rows</li>\n</ul>\n<h2>Accessibility-First Composition</h2>\n<ul>\n<li>Always render semantic HTML (<code>&lt;button&gt;</code>, <code>&lt;a&gt;</code>, <code>&lt;nav&gt;</code>, <code>&lt;main&gt;</code>) before reaching for <code>role</code> attributes</li>\n<li>Every interactive element must be reachable by keyboard</li>\n<li>Form inputs need labels — <code>&lt;label htmlFor&gt;</code> or <code>aria-label</code> if visually labeled by an icon</li>\n<li>Manage focus on route changes and modal open/close</li>\n<li>Run <code>axe</code> in component tests (see <a href=\"../react-testing/SKILL.md\">skills/react-testing</a>)</li>\n<li>Cross-link: <a href=\"../accessibility/SKILL.md\">skills/accessibility/SKILL.md</a> covers WCAG criteria and pattern libraries</li>\n</ul>\n<h2>Routing</h2>\n<p>This skill is router-agnostic. The patterns above work with React Router, TanStack Router, Next.js App Router, Remix Router. Router-specific patterns (loaders, actions, nested layouts) follow the router's documentation — those are framework concerns layered on top of React core.</p>\n<h2>Out of Scope (Pointer Sections)</h2>\n<ul>\n<li><strong>Next.js specifics</strong>: App Router data loading, Route Handlers, Middleware, Parallel Routes — separate concern, use Next.js docs</li>\n<li><strong>React Native</strong>: Platform-specific patterns differ enough to warrant a separate <code>react-native-patterns</code> skill (not present yet)</li>\n<li><strong>Remix</strong>: Loader/action conventions overlap with RSC but follow Remix docs</li>\n</ul>\n<h2>Related</h2>\n<ul>\n<li>Rules: <a href=\"../../rules/react/\">rules/react/</a> — coding-style, hooks, patterns, security, testing</li>\n<li>Skills: <a href=\"../react-performance/SKILL.md\">react-performance</a> for the Vercel-derived performance ruleset, <a href=\"../frontend-patterns/SKILL.md\">frontend-patterns</a> for cross-framework UI concerns, <a href=\"../accessibility/SKILL.md\">accessibility</a>, <a href=\"../angular-developer/SKILL.md\">angular-developer</a> for framework comparison</li>\n<li>Agents: <code>react-reviewer</code> for code review, <code>react-build-resolver</code> for build/bundler errors</li>\n<li>Commands: <code>/react-review</code>, <code>/react-build</code>, <code>/react-test</code></li>\n</ul>\n<h2>Examples</h2>\n<h3>Custom hook for debounced search</h3>\n<pre><code>function useDebounce&lt;T&gt;(value: T, delay = 300): T {\n  const [debounced, setDebounced] = useState(value);\n  useEffect(() =&gt; {\n    const id = setTimeout(() =&gt; setDebounced(value), delay);\n    return () =&gt; clearTimeout(id);\n  }, [value, delay]);\n  return debounced;\n}\n\nfunction SearchBox() {\n  const [query, setQuery] = useState(\"\");\n  const debounced = useDebounce(query, 300);\n  const { data } = useQuery({\n    queryKey: [\"search\", debounced],\n    queryFn: () =&gt; searchApi(debounced),\n    enabled: debounced.length &gt; 0,\n  });\n  return (\n    &lt;&gt;\n      &lt;input value={query} onChange={(e) =&gt; setQuery(e.target.value)} /&gt;\n      &lt;Results items={data ?? []} /&gt;\n    &lt;/&gt;\n  );\n}\n</code></pre>\n<h3>Optimistic UI with React 19 <code>useOptimistic</code></h3>\n<pre><code>\"use client\";\nimport { useOptimistic } from \"react\";\n\nexport function MessageList({ messages }: { messages: Message[] }) {\n  const [optimistic, addOptimistic] = useOptimistic(\n    messages,\n    (state, newMessage: Message) =&gt; [...state, newMessage],\n  );\n\n  async function send(formData: FormData) {\n    const text = String(formData.get(\"text\"));\n    addOptimistic({ id: \"pending\", text, sender: \"me\" });\n    await saveMessage(text);\n  }\n\n  return (\n    &lt;&gt;\n      &lt;ul&gt;{optimistic.map((m) =&gt; &lt;li key={m.id}&gt;{m.text}&lt;/li&gt;)}&lt;/ul&gt;\n      &lt;form action={send}&gt;\n        &lt;input name=\"text\" /&gt;\n        &lt;button type=\"submit\"&gt;Send&lt;/button&gt;\n      &lt;/form&gt;\n    &lt;/&gt;\n  );\n}\n</code></pre>\n<h3>Splitting context to avoid render cascades</h3>\n<pre><code>// Two contexts: one rarely changes, one frequently\nconst ThemeContext = createContext&lt;Theme&gt;(\"light\");\nconst NotificationsContext = createContext&lt;Notification[]&gt;([]);\n\n// A component that only consumes ThemeContext does NOT re-render when notifications change\n</code></pre>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":11466,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:53:13.173564Z","sha256":"2AE045453CC715ACD343CB769719AA9BFE6681BF4CB93C053530AC055C96B97D","sizeBytes":5761},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/react-patterns","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"FBE208B1BD50056E9E9231C15901E8118CA2854557FB37EDB71E2530A1B23F78","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T16:53:34.796701Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/react-patterns"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}