/engsys-web:react-conventionsfrom engsys-web
React + Next.js client conventions (React 19 / Next.js 16+, TanStack Query, Radix UI, shadcn-style cards/dialogs). Use when writing or reviewing React components, hooks, optimistic cache patches, data-fetching code, dialogs, Radix Select usage, JSX, interactive cards/rows, or Next.js 16 proxy.ts / runtime boundary code.
Ships in engsys-web. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Applies to: client components and hooks in the repository's web frontends. Stack assumed: React 19 / Next.js 16+ (App Router, proxy.ts), TanStack Query (React Query), Radix UI primitives, a shared api client helper, and a same-origin BFF/proxy. Test runner is Vitest + Testing Library (see the sibling frontend-testing skill).
Naturalize: confirm framework versions, the query-client setup, and the shared API helper path in
CLAUDE.md. Paths below (apps/web/lib/...) are illustrative.
An optimistic React Query patch is a hand-written mirror of the server's write. It is correct only when it touches every surface the mutation touches:
[...nodes].sort(sortFn).queryClient.invalidateQueries({ queryKey: queryKeys.nodes.stats(scopeId) })).optimisticId at onMutate time and match by node.id === optimisticId only — never by label or array index.[...arr].sort(fn) and { ...obj, field: x }.// Wrong — mutates the cached array in place, no sibling refresh
const node = cache.find((n) => n.id === id);
node.sortOrder = next;
updated.sort(sortDepth1);
// Right — new references, re-sort a copy, refresh siblings
const patched = cache.map((n) => (n.id === id ? { ...n, sortOrder: next } : n));
const sorted = [...patched].sort(sortDepth1);
queryClient.setQueryData(listKey, sorted);
queryClient.invalidateQueries({ queryKey: queryKeys.nodes.stats(scopeId) });
Cache-KEY completeness: any new query parameter that changes the result set MUST be included in the cache key so distinct filter values never collide on one cached entry.
When a mutation on a child rolls up into a parent summary field, re-derive the parent field from the full updated state, not from the mutation result alone:
// Wrong — ignores an already-decided primary child item
const newStatus = remainingPending.length > 0 ? "PENDING" : result.status;
// Right — inherit the primary item's decided status; fall back to result when none decided yet
const primaryDecidedStatus = parent.primaryItemId
? parent.decidedItems?.find((item) => item.id === parent.primaryItemId)?.status
: undefined;
const newStatus =
remainingPending.length > 0 ? "PENDING" : (primaryDecidedStatus ?? result.status);
Apply identical derived-state logic to both the list cache and the detail cache (STATUS_PRECEDENCE_RANK).
Never silently return null on a fetch error for primary content — the user gets a blank section with no signal. Handle isError with user-visible UI (null is acceptable only for decorative secondary tiles):
const { data, isError } = useAccountInvoices();
// Primary content card — show an explicit error state and recovery hint:
if (isError) {
return (
<Card>
<CardHeader><CardTitle>Invoices</CardTitle></CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Could not load invoices. Please refresh the page to try again.
</p>
</CardContent>
</Card>
);
}
A confirm dialog for a destructive action (remove/suspend/delete) must own its own isPending and error state — not inherit them from the parent, and not route failures to a toast that leaves the modal open with no inline explanation:
async function handleConfirm() {
setError(null);
setIsPending(true);
try {
await onConfirm(); // throws on failure
onOpenChange(false); // success closes the dialog
} catch (err) {
setError(errorMessage(err)); // failure stays open, shows inline
} finally {
setIsPending(false);
}
}
React 19 / Next.js 16+ eslint rules ratchet react-hooks/set-state-in-effect and react-hooks/cannot-access-refs-during-render to error:
handleOpenChange(next)).useMemo + controlled fallback (const effective = form.value || derivedDefault).startTransition:
import { startTransition, useEffect } from "react";
useEffect(() => {
startTransition(() => setShown(PAGE_SIZE));
}, [period, scopeId]);
saving/pending flag in both the success path and the open-reset callback.A controlled Radix <Select value={x} onValueChange={setter}> inside a <form> with an empty initial value fires a spurious onValueChange("") when its hidden <select> remounts:
<Select
value={form.unit}
onValueChange={(v) => {
if (v) patch({ unit: v }); // guard against Radix's empty remount event
}}
>
{/* ... */} is a JSX expression node. Put comments outside the ternary or wrap the branch in a fragment:
// Right — comment outside the ternary, or wrap the branch in a fragment
{kind === "badge" ? (
<>
{/* comment */}
<StatusBadge variant={variant!} />
</>
) : null}
<a>/<button> inside <a>/<button>).stopPropagation on nested control clicks and verify with keyboard (Enter and Space).aria-controls={expanded ? regionId : undefined}.As documented in web-platform-conventions, Next.js 16 replaced legacy middleware.ts with proxy.ts (running on the Node.js runtime by default). If any route or helper is configured to run in an Edge or client-shared bundle, never place top-level database or native Node imports at module scope where restricted bundlers evaluate them on load:
// Right — lazy import inside server-only helper when shared across runtime boundaries
export async function ensureSessionClaimed(id: string) {
const { getPrisma } = await import("./prisma");
const prisma = await getPrisma();
return prisma.session.findUnique({ where: { id } });
}
Use the shared api helper (api.get/post/put/delete) for all client → gateway calls, never raw fetch. The helper provides 401 token refresh, tenant header injection (X-Tenant-Id), correlation-id forwarding, and structured error parsing:
// Wrong — bypasses auth refresh + tenant headers
const res = await fetch("/api/proxy/api/v1/reports/export", {
method: "POST", credentials: "include", body: JSON.stringify(payload),
});
// Right — the helper prepends the proxy prefix and handles auth/headers/errors
const result = await api.post<ExportReportResult>("/api/v1/reports/export", payload);
When adding a query parameter or response field on the client, implement and test it at the owning backend service in the same PR.
arr.sort(), obj.x = y).queryKey.return null on isError for primary user-facing content.setState inside useEffect instead of close callbacks / useMemo / startTransition.onValueChange on a controlled empty-start Radix Select inside a <form>.{/* comment */} directly inside a JSX ternary branch.aria-controls IDs.fetch instead of the shared api client helper.queryKeyisError renders a visible error state for primary contentisPending + inline error and resets on closereact-hooks/set-state-in-effect violations<form> guards onValueChange against ""aria-controls gated on target DOM presenceproxy.ts (never legacy middleware.ts)api helper with async/awaitWhat SKILL.md sets; muted values are Claude Code's defaults
3 skills in this plugin
/frontend-testingFrontend test discipline — Vitest 4, Testing Library (RTL / React Testing Library), and Playwright E2E for React / Next.js apps. Use when writing or reviewing Vitest specs, vi.mock factories, fake-timer tests, RTL component tests, Radix portal tests, or Playwright E2E specs and their CI matrix wiring./web-platform-conventionsWeb platform conventions for this repo — Content-Security-Policy discipline and (for Next.js 16+) the proxy.ts-not-middleware convention. Use when editing CSP headers, adding a third-party SDK / analytics / external API origin, touching request-edge code (middleware/proxy), or wiring auth/redirects/headers on a web frontend.Other plugins' skills for the same job
npx claudepluginhub eric-sabe/engsys --plugin engsys-web