react-best-practices
Skill0 starsChanged 4 months agoMITView on GitHub
React/TypeScript engineering standard for Vite + React 18 SPAs built with Refine, MUI, react-hook-form, and react-router v6. Load BEFORE writing, modifying, or reviewing any React code in such an app — anything under src/ (pages/, components/, providers/, hooks) or any .tsx/.ts component, hook, data fetch, form, MUI DataGrid, or theme change. Covers component architecture, naming, state management, TypeScript, error handling, forms, testing, security, accessibility, performance (waterfalls, bundle size, re-renders), and tooling gates.
- Reads credentials
38 other projects use a version of this.
Adopted by
Most recently taken up by
- baekenough/oh-my-customcodetheir own version, first seen Oct 3, 2026
- BytePioneer-AI/codex-hosttheir own version, first seen Oct 2, 2026
- laguagu/claude-code-nextjs-skillstheir own version, first seen Sep 30, 2026
- Isabella-a/Skillstheir own version, first seen Sep 27, 2026
- sabahattink/antigravity-fullstack-hqtheir own version, first seen Sep 20, 2026
- drinkspiller/skillstheir own version, first seen Sep 16, 2026
Used with
Projects with it also use parallel-agents, web-design-guidelines and 8 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
parcadeiSkillparallel-agents
Parallel Agent Orchestration
Also in 3 projects that use this
VercelSkillweb-design-guidelines
Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
Also in 7 projects that use this
JetBrainsSkillwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
Also in 7 projects that use this
xfstudioSkillclean-code
Pragmatic coding standards - concise, direct, no over-engineering, no unnecessary comments
Also in 3 projects that use this
ttmouseSkillnotebooklm
Automate Google NotebookLM - create notebooks, add sources, generate podcasts/videos/quizzes, download artifacts. Supports browser-based content extraction for anti-crawler platforms (Twitter/X, LinkedIn, etc.). Activates on explicit /notebooklm or intent like "create a podcast about X
Also in 3 projects that use this
MicrosoftSkillmcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
Also in 6 projects that use this
Other versions38 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 38
- openai/plugins★ 7.3ksame name
- BytePioneer-AI/codex-host★ 2.7ksame name
- vercel/vercel-plugin★ 297same name
- mxyhi/token_proxy★ 94same name
- laguagu/claude-code-nextjs-skills★ 67same name
- baekenough/oh-my-customcode★ 43same name
- tdimino/claude-code-minoan★ 40same name
- itallstartedwithaidea/agent-skills★ 39same name
- ttmouse/skills★ 34same name
- sabahattink/antigravity-fullstack-hq★ 30same name
28 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository7 other files it gives its agents.
The file
Show its rules and text
We split this skill into the rules it gives an agent
21 rules. 0 are common, 6 are distinctive, and 15 are very specific to this project.
0
Common
Most of the 33 edited versions we read keep these.
6
Distinctive
This author's own choices. Worth a look.
15
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 13
When this conflicts with an in-repo convention, follow the repo and say so.
- Very specific: line 28
Import through the @/* → src/* alias, not ../../..
- Very specific: line 30
Never suggest Next.js/RSC/SSR concepts ("use client", server actions, hydration, next/*): lazy-load with React.lazy.
- Very specific: line 37
Prefer children/slots to a variant-plus-boolean-flags API.
- Very specific: line 38
Never define a component inside a component, including DataGrid cell and slot renderers: renderCell, plus slots/slotProps on …
- Very specific: line 40
Never && with a numeric left side ({count && <X/>} renders 0).
- Very specific: line 52
Never mutate props, state or Refine query results (the shared TanStack Query cache) in place with .sort()/.reverse()/splice.
- Very specific: line 57
Keep strict: true. No any.
- Very specific: line 62
Never @ts-ignore; @ts-expect-error with a reason comment if truly needed.
- Distinctive: line 68
Every mutation handles failure: show a message, keep the user's input, re-enable the control.
- Distinctive: line 71
Every request has a timeout.
- Very specific: line 96
Start independent requests together (Promise.all).
- Very specific: line 99
Import concrete MUI modules (@mui/material/Button, @mui/icons-material/Delete), not the barrel.
- Very specific: line 108
Never silence react-hooks/exhaustive-deps by dropping a dependency.
- Very specific: line 118
Every VITE_ variable in import.meta.env ships to the browser: public config only, never API keys or signing secrets.
- Very specific: line 125
Every input has a programmatically associated label.
- Distinctive: line 127
Never remove a focus outline without a replacement, and never let a focused row or field end up entirely hidden behind a sticky AppBar, a …
- Very specific: line 131
Avoid autoFocus without a deliberate UX reason.
- Distinctive: line 135
Run from the app root:
- Very specific: line 145
Never add eslint-disable without a reason comment.
- Distinctive: line 149
Never invent business rules (credit limits, tax, rounding, status transitions, SLAs).
“Common” is measured: kept by at least 6 in 10 of the 33 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
React Best Practices (Vite + Refine + MUI SPA)
Vite + React 18 SPA (not Next.js), TypeScript 5.4 strict: true, @refinedev/core + @refinedev/mui, MUI 5 (@mui/material, @mui/x-data-grid, @mui/x-date-pickers), react-hook-form, react-router-dom v6, axios, dayjs.
When this conflicts with an in-repo convention, follow the repo and say so.
1. Stack Boundaries & Layout
src/
pages/<feature>/ # route screens: <Feature>Page.tsx
components/ # feature-local components
components/common/, components/layout/
providers/ # Refine data/auth providers (dataProvider.ts, authProvider)
interfaces/ # shared domain types
config/, theme/, utils/- New feature →
pages/<feature>/<Feature>Page.tsx+components/; reusable across features →components/common/; shared types →interfaces/. Never create a parallel tree. - Import through the
@/*→src/*alias, not../../..chains. - Money is INR: format through one shared
Intl.NumberFormat("en-IN", {style:"currency", currency:"INR"})formatter; never hand-concatenate a symbol or float-accumulate currency. - Never suggest Next.js/RSC/SSR concepts (
"use client", server actions, hydration,next/*): lazy-load withReact.lazy; putdefer/asyncscripts and<link rel="preconnect">/<link rel="preload">inindex.html. No SWR: Refine wraps TanStack Query, which already dedupes and caches. - React 18 is pinned; its docs are
https://18.react.dev(react.dev documents 19.x). React-19-only, unavailable here: Actions (async functions instartTransition),useActionState,useOptimistic,useDeferredValue(value, initialValue),use,refas a prop, ref cleanup functions,react-dompreload/preconnect,useEffectEvent, and<Activity>(instead keep an expensive tab panel mounted and hide it with CSS, or hoist its state above the tab switch).
2. Components & Naming
- Extract past these limits: component file ≤ 250 lines; component function ≤ 120 lines and ≤ 5 hooks doing unrelated work; JSX nesting ≤ 4; ≤ 8 props (group into an object or split). Never grow a file already over a limit: extract the part you touch into
pages/<feature>/components/. - A page composes, child components render sections, custom hooks own data and logic: when a component both fetches/derives and renders a large JSX tree, the fetch/derive half becomes
use<Feature>()in the feature folder. - Prefer
children/slots to a variant-plus-boolean-flags API; past 2 levels of prop drilling, use context or restructure. - Never define a component inside a component, including DataGrid cell and slot renderers:
renderCell, plusslots/slotPropson@mui/x-data-gridv6+ orcomponents/componentsPropson v5 (check the installed major). Hoist, oruseCallback. - Naming: internal handlers
handle*(handleSubmit), callback propson*(onApprove); noIprefix on types or interfaces; units in the name (timeoutMs,amountInr); component file named after its component (CreditProfileCard.tsx), notindex.tsx. - Never
&&with a numeric left side ({count && <X/>}renders0); use a ternary.
3. State Management
Pick the location in this order:
- Server state → Refine hooks (
useList,useOne,useCustom,useUpdate). Never copy fetched data intouseState; never hand-rolluseEffect+axios+setState. - URL state →
useSearchParams: filters, pagination, sort, active tab and selected-row id live in the URL, notuseState. - Local UI state (open/closed, hover, draft input) →
useStatein the nearest owner;useReduceronce 3+ fields change together or transitions have rules. - Cross-cutting → context, sparingly (auth/user, theme, notifications): one provider per concern, memoized value.
- Derive during render; effects only synchronize with external systems, never
useEffect+setStateto compute or sync state. Reset child state on identity change with akey. - Never mutate props, state or Refine query results (the shared TanStack Query cache) in place with
.sort()/.reverse()/splice; copy first ([...rows].sort(...)). - Persisted
localStoragedata is versioned and minimal, read once into memory, never in a render path.
4. TypeScript
- Keep
strict: true. Noany; an unavoidable one carries a justifying comment. - Type API responses at the boundary in
interfaces/; don't letanyfromaxios/dataProviderreach components. - Model mutually exclusive states as discriminated unions (
{status:"loading"} | {status:"error"; error:E} | {status:"ok"; data:D}), not optional flags. typefor unions/aliases,interfacefor object shapes that may be extended;import typefor type-only imports (lint enforces).- Type props explicitly; no
React.FC.@types/react18 has no implicitchildren: declarechildren: React.ReactNodewhen accepted. Extend MUI props withComponentProps<typeof X>(ComponentPropsWithoutRef/ComponentPropsWithRefwhen ref forwarding matters) rather than restating them. - Never
@ts-ignore;@ts-expect-errorwith a reason comment if truly needed.
5. Error Handling & Resilience
- Error boundaries around the app shell and each independently failing panel. A failed
React.lazychunk load throws to the nearest boundary, so pair every<Suspense>with one. - Map statuses once, in the data provider or axios interceptor:
401→ re-auth;403→ forbidden view (aforbidden/route);422→ field errors on the form;5xx/network → retryable "something went wrong". Never render raw backend errors or stack traces. - Every mutation handles failure: show a message, keep the user's input, re-enable the control.
- Auto-retry only idempotent reads (GET), bounded with backoff; never auto-retry a non-idempotent write (credit approval, invoice post).
- Creating
POSTs send anIdempotency-Keygenerated once per submitted set of values and reused when the user resends after a timeout or network error; never mint one per request in an interceptor. - Every request has a timeout; no response is an error state, not a permanent spinner.
- Loading, empty and error are three distinct states; never show empty for an error.
- Log with
console.errorand context; never log PII or tokens.
6. Forms & Validation (react-hook-form)
- A schema (zod/yup + resolver) is the single source of validation rules; infer the TS type from it.
- Disable submit while
isSubmitting, which holds only while the submit handler's promise is pending:await mutateAsync(...)(or return Refine'sonFinish, which waits only under the defaultpessimisticmutationMode), never a fire-and-forgetmutate(). - Map a 422's field errors onto fields with
setError, plus a form-level message for non-field errors; never collapse them into a toast. Controllerfor MUI inputs that don't expose the native input's ref (Select,Autocomplete,DatePicker,Checkbox/Switchgroups): the trigger is ref exposure, not controlled-ness. PlainTextFieldtakes{...register("field")}directly.useWatchon the specific field; neverwatch()the whole form.- Warn on navigate-away when
isDirty;reset()after a successful submit. - Money/quantity inputs: parse and validate as fixed precision, enforce min/max/step, reject negatives explicitly rather than relying on the input type.
- Dates: the backend stores UTC. Convert at the boundary with
dayjs(plugins registered once at app setup) and an explicit timezone; naive local parsing produces off-by-one-day dates.
7. Testing
- Vitest + React Testing Library +
@testing-library/user-event, with MSW mocking the API at the network layer. If none is configured, say so. - Query by role/label/text (
getByRole("button", {name:/approve/i})); never assert on state internals or snapshot whole trees. - Cover per feature: happy path; empty, loading and error states; validation failures; permission-denied (RBAC) rendering; money/rounding edges. Test custom hooks directly with
renderHook. - Deterministic (fake timers, fixed clock, no network, no
sleep; factories over giant literal fixtures); every bug fix ships a regression test that fails before the fix. - Adding coverage to an untested codebase: money/credit logic → form validation → status transitions → table filtering. Never chase a coverage % on presentational markup.
8. Performance
- Start independent requests together (
Promise.all); neverawaitinside a loop over rows. React.lazyper route (pages/<feature>) and for heavy or rarely used UI: DataGrid screens, date pickers, charts, export/print views, large dialogs, admin-only modules.import()paths are static literals, never template strings.- On React 18,
<Suspense>suspends only forReact.lazychunks and a data layer opted into suspense (TanStack Query v5useSuspenseQueryunder Refine 5;suspense: trueon v4 under Refine 4), never a bare promise; otherwise each panel owns its own loading state. Give each independently loading region (lazy dialog, tab, chart panel) its own<Suspense>, or it falls back to the route boundary and blanks the page. - Import concrete MUI modules (
@mui/material/Button,@mui/icons-material/Delete), not the barrel. This is a lint and dev-server-speed win (worst with@mui/icons-material), not shipped bytes: Vite tree-shakes barrels in production, so never call it a bundle win without avite buildmeasurement. Type-only barrels (interfaces/) are exempt. - Refine generates query keys from hook props (
resource,filters,sorters,pagination,id): pass parameters as props, never close over them in a fetch. A hand-written key (useCustom, rawuseQuery) includes every result-affecting parameter (filters, pagination, customer id). - Paginate and filter large tables server-side; after a mutation, invalidate only the affected resource/id.
- Against a cursor API (
page_token/next), the URL holdspage_sizeand the currentpage_token(passed to the data provider viameta), never a page number the API cannot resolve; an expired-token400resets to the first page. memo/useMemo/useCallbackonly for measured-expensive work or an identity another rule needs (context value, grid renderer, effect dependency); never memo a primitive expression.- React Compiler supports React 18 (
target: "18"plusreact-compiler-runtime); when enabling it, keep existing memoization.
9. Hooks Correctness
- Never silence
react-hooks/exhaustive-depsby dropping a dependency; fix the design (hoist, ref, functional update, stable callback). - Hoist non-primitive fallbacks that feed a dependency array or a
memochild to module scope (const EMPTY: readonly Ticket[] = [];data?.data ?? EMPTY), never an inline[]/{}default. - Clean up every listener, timer and subscription, and abort or ignore stale in-flight responses so a slow earlier one can't overwrite newer state. React 18.0 removed the setState-on-unmounted-component warning, so a missing cleanup fails silently.
- Stable callbacks without stale closures (React 18's substitute for
useEffectEvent): keep the latest handler in a ref, assigned in an effect rather than during render, and callref.current, so a subscribing effect doesn't list the handler as a dependency. - App-wide init runs once per page load: top level of the entry module or behind a module-level
didInitguard, never an unguardeduseEffect([]).
10. Security
- No
dangerouslySetInnerHTMLwith server or user content; if unavoidable, sanitize with DOMPurify and justify in a comment. - Client-side validation and RBAC checks are UX only, never enforcement; the backend authorizes every action.
- Every
VITE_variable inimport.meta.envships to the browser: public config only, never API keys or signing secrets. - Tokens: prefer httpOnly cookies; with
localStorage, accept the XSS exposure, keep TTLs short, clear on logout. Never put a token in a URL or query param. - Allow-list any URL used in
href/src/redirects (blockjavascript:and open redirects);rel="noopener noreferrer"ontarget="_blank".
11. Accessibility (WCAG 2.2 AA)
- Interactive elements are semantic (
button,a, MUIButton/IconButton/CardActionArea), never anonClickon adiv/Box/Card/TableRow; everything is keyboard operable. - Every input has a programmatically associated label. Errors identify the field and describe the problem in text; link the message with
aria-describedby(oraria-errormessage; pick one and stay consistent) and setaria-invalid, but not on an untouched required field before a submit attempt. - Icon-only buttons need an accessible name (
aria-label). - Never remove a focus outline without a replacement, and never let a focused row or field end up entirely hidden behind a sticky AppBar, a sticky DataGrid header or an open Snackbar.
- MUI
Dialogmoves focus in, traps it and restores it on close: setdisableAutoFocus/disableEnforceFocus/disableRestoreFocusonly with a documented reason, and keep it dismissible with Escape plus a visible Cancel/Close. It wiresaria-labelledbyonly to aDialogTitlechild without its ownid: a custom title id, or a dialog titled any other way, needs explicitaria-labelledby, and descriptive body text needsaria-describedby. - Contrast: text ≥ 4.5:1 (large text, ≥ 18pt or ≥ 14pt bold, ≥ 3:1); non-text parts ≥ 3:1 against adjacent colours (chip fills and borders, icon glyphs, input outlines, focus rings). Never convey status or an error by colour alone; add text or an icon.
- Announce async results with a toast /
role="status"so a screen-reader user learns a save succeeded without focus moving. - Avoid
autoFocuswithout a deliberate UX reason.
12. Tooling Gates
Run from the app root:
npm run typecheck # tsc --noEmit
npm run lint # eslint src --max-warnings 0
npm run build # tsc && vite build
# npm test # once Vitest is set up- Inherited debt (pre-existing
anys, MUI barrel imports, lint warnings): measure it on an unmodified checkout, add none, reduce it in files you touch.--max-warnings 0fails the whole command on a non-zero baseline, and a gate already red before your change is no signal: gate on your files (npm run lint <paths>,tsc --noEmitoutput filtered to them). - Never add
eslint-disablewithout a reason comment; never disable a rule repo-wide to go green.
13. Agent Rules
- Never invent business rules (credit limits, tax, rounding, status transitions, SLAs); ask.
- Flag security-relevant changes (auth, RBAC display, tokens,
dangerouslySetInnerHTML, URL handling) in your summary.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

