Write React the way React wants to be written
Most React bugs break the Rules of React: components and hooks must be pure
(same inputs → same output, no side effects during render), props and state are
immutable snapshots, and hooks are called unconditionally at the top level of a
component or custom hook. Model UI as a function of state, keep effects for
synchronising with systems outside React, and compose small components. This pack sits
on top of the typescript-conventions skill; the design bar is frontend-foundations.
Steps
- Read the repo's React set-up. React version (19.x adds Actions,
use, ref-as-prop;
19.2 adds useEffectEvent and <Activity>), whether the React Compiler is enabled
(babel/SWC plugin in the build config), eslint-plugin-react-hooks config, framework
(Next.js App Router, Remix/React Router, Vite SPA), and the state/data libraries (the
frontend-state-management and frontend-data-fetching skills). Call search_lore
and copy a sibling component's shape.
- Keep render pure. No fetches, subscriptions,
Math.random()/Date.now() for
output, or mutation of props, state or module variables during render. Never mutate
state in place (items.push); create a new value. Strict Mode double-invokes render and
effects in development precisely to expose impurity — "the effect runs twice" means the
effect lacks a correct cleanup, not that Strict Mode should be removed.
- You probably don't need that effect. Before writing
useEffect, check:
- Derived from props/state? Compute it during render (
useMemo only if measured as
expensive and the Compiler is off).
- Caused by a user action? Put it in the event handler.
- Reset when an id changes? Key the component by the id.
- Fetching? Use the data layer, a loader, or a Server Component.
Effects remain for synchronisation: subscriptions, timers, imperative widgets, DOM
measurement (
useLayoutEffect only when you must measure before paint). Every effect
that starts something returns a cleanup that stops it.
- Honest dependencies. The array lists every reactive value the effect reads; never
disable
react-hooks/exhaustive-deps. Logic that must read the latest value without
re-running the effect (logging, analytics, a callback prop) goes in useEffectEvent
(React 19.2+) or a ref updated in an effect on older versions. Move pure helpers outside
the component instead of wrapping them in useCallback.
- Memoisation policy. With the React Compiler on, do not add
memo/useMemo/
useCallback by hand unless profiling shows the Compiler bailed out; fix the lint
diagnostics that cause bail-outs instead. With it off, memoise only what the profiler
shows is costly (the frontend-performance skill).
- Keys are identities. Use stable ids from the data; never array indexes for lists
that reorder, filter or delete, and never generated keys (
Math.random()) — both lose
input state and focus.
- Compose instead of configuring.
children and slot props over boolean variant
props; custom hooks (named useX, calling hooks) for reusable stateful logic; context
for rarely changing shared values, split by change frequency. In React 19 ref is a
prop (no forwardRef) and <Context value> is the provider.
- Forms and mutations with Actions where the repo uses them:
useActionState for
submit-with-result, useFormStatus for a pending button in a child, useOptimistic
for an optimistic value that reverts when the action settles. Otherwise follow the
repo's form library (the frontend-forms-and-validation skill).
- Async boundaries.
<Suspense> with a real fallback around the part that waits and
an error boundary at route or section level; startTransition/useDeferredValue for
non-urgent updates so typing stays responsive. No async function passed directly to
useEffect; an inner async function checks a cancelled flag or AbortSignal.
- Server Components (Next.js App Router, RSC). Server by default.
"use client"
marks a module boundary — push it to the interactive leaves; everything passed across
it must be serialisable. Import server-only code through modules guarded with
import 'server-only'. "use server" functions (Server Functions/Actions) are public
HTTP endpoints: authenticate, authorise and validate their arguments inside the
function every time (the security-authz and security-input-validation skills).
Render nothing that differs between server and client (time, locale, window) without
a client-only boundary, or hydration fails.
- Test and evidence. Per AC, a component test through the rendered UI (the
frontend-testing skill); run type-check, lint (hooks rules included) and tests.
Record per-AC evidence with the record-evidence skill, then stop.
Review checklist
A reviewer blocks on an item only when it causes a bug (stale value, leak, lost input,
hydration failure, missing auth), breaks an AC or leaves one untested; the memoisation
item is guidance.
- Render is pure; no state mutated in place; no side effects outside effects/handlers.
- No effect that mirrors props or state into other state, or handles a user event.
- Every effect that subscribes or starts a timer cleans up; dependency lint not silenced.
- Keys are stable data ids.
- Manual memoisation justified by the Compiler being off plus a profile.
- Client boundaries at the leaves; Server Functions check auth and validate input.
- Suspense/error boundaries have real fallbacks; no hydration-mismatching output.
Done when
Lint (including react-hooks) and type-check are clean with no new suppressions, each AC
has a behaviour test, and the review checklist holds for the diff.
Capture lore
This skill is one of the places durable, reusable knowledge naturally surfaces:
While copying a sibling component you learn the component structure, the provider layout and where the client/server boundaries sit. That kind of fact is lore. Capture it via the lore-capture
protocol in your brief (CLAUDE.factory.md, step 11 "Memory contribution"):
call the Memory MCP suggest_lore once at the close of your work — reusable
conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.
1---2name: react-patterns3description: Use when a ticket adds or changes React code — components, hooks, effects, context, actions and forms, server components, suspense boundaries — and it must follow the Rules of React and modern React 19 idioms (pure render, effects only for synchronisation, derived state computed not stored, stable keys, composition over configuration) as the framework pack for any React or Next.js change. Invoke for "build this in React", "the effect runs twice", "too many re-renders", or as the React layer on top of typescript-conventions.4stack: [react, next, nextjs, web]5area: frontend6metadata:7 source: https://skillmd.com/skills/tmj-90/react-patterns8---910# Write React the way React wants to be written1112Most React bugs break the **Rules of React**: components and hooks must be pure13(same inputs → same output, no side effects during render), props and state are14immutable snapshots, and hooks are called unconditionally at the top level of a15component or custom hook. Model UI as a function of state, keep effects for16synchronising with systems outside React, and compose small components. This pack sits17on top of the `typescript-conventions` skill; the design bar is `frontend-foundations`.1819## Steps20211. **Read the repo's React set-up.** React version (19.x adds Actions, `use`, ref-as-prop;22 19.2 adds `useEffectEvent` and `<Activity>`), whether the **React Compiler** is enabled23 (babel/SWC plugin in the build config), `eslint-plugin-react-hooks` config, framework24 (Next.js App Router, Remix/React Router, Vite SPA), and the state/data libraries (the25 `frontend-state-management` and `frontend-data-fetching` skills). Call `search_lore`26 and copy a sibling component's shape.272. **Keep render pure.** No fetches, subscriptions, `Math.random()`/`Date.now()` for28 output, or mutation of props, state or module variables during render. Never mutate29 state in place (`items.push`); create a new value. Strict Mode double-invokes render and30 effects in development precisely to expose impurity — "the effect runs twice" means the31 effect lacks a correct cleanup, not that Strict Mode should be removed.323. **You probably don't need that effect.** Before writing `useEffect`, check:33 - Derived from props/state? Compute it during render (`useMemo` only if measured as34 expensive and the Compiler is off).35 - Caused by a user action? Put it in the event handler.36 - Reset when an id changes? Key the component by the id.37 - Fetching? Use the data layer, a loader, or a Server Component.38 Effects remain for synchronisation: subscriptions, timers, imperative widgets, DOM39 measurement (`useLayoutEffect` only when you must measure before paint). Every effect40 that starts something returns a cleanup that stops it.414. **Honest dependencies.** The array lists every reactive value the effect reads; never42 disable `react-hooks/exhaustive-deps`. Logic that must read the latest value without43 re-running the effect (logging, analytics, a callback prop) goes in `useEffectEvent`44 (React 19.2+) or a ref updated in an effect on older versions. Move pure helpers outside45 the component instead of wrapping them in `useCallback`.465. **Memoisation policy.** With the React Compiler on, do not add `memo`/`useMemo`/47 `useCallback` by hand unless profiling shows the Compiler bailed out; fix the lint48 diagnostics that cause bail-outs instead. With it off, memoise only what the profiler49 shows is costly (the `frontend-performance` skill).506. **Keys are identities.** Use stable ids from the data; never array indexes for lists51 that reorder, filter or delete, and never generated keys (`Math.random()`) — both lose52 input state and focus.537. **Compose instead of configuring.** `children` and slot props over boolean variant54 props; custom hooks (named `useX`, calling hooks) for reusable stateful logic; context55 for rarely changing shared values, split by change frequency. In React 19 `ref` is a56 prop (no `forwardRef`) and `<Context value>` is the provider.578. **Forms and mutations with Actions** where the repo uses them: `useActionState` for58 submit-with-result, `useFormStatus` for a pending button in a child, `useOptimistic`59 for an optimistic value that reverts when the action settles. Otherwise follow the60 repo's form library (the `frontend-forms-and-validation` skill).619. **Async boundaries.** `<Suspense>` with a real fallback around the part that waits and62 an error boundary at route or section level; `startTransition`/`useDeferredValue` for63 non-urgent updates so typing stays responsive. No `async` function passed directly to64 `useEffect`; an inner async function checks a cancelled flag or `AbortSignal`.6510. **Server Components (Next.js App Router, RSC).** Server by default. `"use client"`66 marks a module boundary — push it to the interactive leaves; everything passed across67 it must be serialisable. Import server-only code through modules guarded with68 `import 'server-only'`. `"use server"` functions (Server Functions/Actions) are public69 HTTP endpoints: authenticate, authorise and validate their arguments inside the70 function every time (the `security-authz` and `security-input-validation` skills).71 Render nothing that differs between server and client (time, locale, `window`) without72 a client-only boundary, or hydration fails.7311. **Test and evidence.** Per AC, a component test through the rendered UI (the74 `frontend-testing` skill); run type-check, lint (hooks rules included) and tests.75 Record per-AC evidence with the `record-evidence` skill, then stop.7677## Review checklist7879A reviewer blocks on an item only when it causes a bug (stale value, leak, lost input,80hydration failure, missing auth), breaks an AC or leaves one untested; the memoisation81item is guidance.8283- Render is pure; no state mutated in place; no side effects outside effects/handlers.84- No effect that mirrors props or state into other state, or handles a user event.85- Every effect that subscribes or starts a timer cleans up; dependency lint not silenced.86- Keys are stable data ids.87- Manual memoisation justified by the Compiler being off plus a profile.88- Client boundaries at the leaves; Server Functions check auth and validate input.89- Suspense/error boundaries have real fallbacks; no hydration-mismatching output.9091## Done when9293Lint (including `react-hooks`) and type-check are clean with no new suppressions, each AC94has a behaviour test, and the review checklist holds for the diff.9596## Capture lore9798This skill is one of the places durable, reusable knowledge naturally surfaces:99**While copying a sibling component you learn the component structure, the provider layout and where the client/server boundaries sit.** That kind of fact is *lore*. Capture it via the **lore-capture100protocol in your brief** (`CLAUDE.factory.md`, step 11 "Memory contribution"):101call the Memory MCP `suggest_lore` once at the close of your work — reusable102conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.