React Development
Purpose
This skill governs the design, implementation, and optimization of React applications at production quality. It applies equally to greenfield work and iterative feature development. Agents loading this skill are expected to produce components that are composable, testable, accessible, and performant by default — not as afterthoughts.
When to Activate
- Creating or modifying React components (
.tsx,.jsx) - Implementing client-side state management
- Writing custom hooks or composing existing ones
- Adding data-fetching logic with React Query or SWR
- Optimizing rendering performance or addressing re-render bugs
- Setting up error boundaries or Suspense-based loading
- Writing component tests with Testing Library
Required Workflow
-
Classify the component before writing any code. Determine: Is it purely presentational (no state, only props)? A stateful container? A data-fetching boundary? A layout primitive? Name and structure it accordingly.
-
Define the prop interface first using TypeScript. Use
interfacefor component props (extendable),typefor unions and computed prop shapes. Mark optional props explicitly with?. Never useany. -
Choose the right state primitive:
useStatefor simple local UI state (toggles, form inputs, counters)useReducerwhen state has multiple sub-values or transitions are complex (form wizard, multi-step flows)- React Context for subtree-scoped shared state (theme, locale, auth user)
- Zustand or Jotai for cross-cutting client state that multiple unrelated trees need
- React Query (
@tanstack/react-query) or SWR for all server-derived state — never store fetched data inuseState
-
Write the component shell with correct file structure:
ComponentName/ index.tsx ← public export ComponentName.tsx ← implementation ComponentName.test.tsx ComponentName.stories.tsx (if Storybook present) -
Implement hooks following the Rules of Hooks strictly:
- Only call hooks at the top level — no conditionals, no loops, no nested functions
- Every
useEffectmust declare a complete dependency array; never suppress lint warnings without a documented reason - Cleanup side effects: return a cleanup function from every
useEffectthat sets up subscriptions, timers, or event listeners - Use
useReffor values that must persist across renders without triggering re-renders (DOM refs, timer IDs, previous values)
-
Implement memoization surgically, not by default:
React.memoon a component only when its parent re-renders frequently and its own props are stableuseMemoonly for expensive computations (sort/filter of large arrays, complex derivations) — verify with profiler firstuseCallbackonly when a callback is a dependency of another hook or passed to a memoized child- Premature memoization increases complexity without benefit; profile first
-
Add error boundaries at logical subtree roots. Use a class component or the
react-error-boundarylibrary (ErrorBoundary+useErrorBoundary). Provide afallbackprop with a meaningful recovery UI, not just "Something went wrong." -
Implement Suspense boundaries for async data and lazy-loaded components. Place
<Suspense fallback={<Skeleton />}>as close to the loading component as possible to minimize UI freeze surface. -
Write tests using
@testing-library/react. Every component gets at minimum: render test, interaction test (user events), and async state test where applicable. UseuserEventoverfireEventfor realistic interaction simulation. -
Run validation before marking complete:
npx tsc --noEmit # type check npx eslint src/ # lint npx vitest run # or jest
Engineering Standards
Component Composition
- Prefer composition over configuration: use
children, render props, or compound components rather than boolean prop explosion (showHeader,showFooter,hasIconon a single component) - Compound component pattern for complex widgets:
<Tabs> <Tabs.List> <Tabs.Tab>Overview</Tabs.Tab> </Tabs.List> <Tabs.Panel>...</Tabs.Panel> </Tabs> - Keep components focused: a component that fetches data, transforms it, renders a form, and handles submission is four components, not one
- Extract reusable logic into custom hooks (
usePagination,useDebounce,useLocalStorage)
Custom Hooks
- Custom hook filenames:
use[Name].ts— never put JSX in a custom hook - Return stable references: memoize returned objects/arrays with
useMemoif the hook is performance-sensitive - Document the hook's contract: what it needs, what it returns, what side effects it produces
- Test custom hooks in isolation with
renderHookfrom@testing-library/react
State Management Decision Matrix
| Scope | Complexity | Tool |
|---|---|---|
| Single component | Low | useState |
| Single component | High | useReducer |
| Subtree | Any | React Context + useReducer |
| App-wide UI state | Medium | Zustand |
| App-wide fine-grained | High | Jotai |
| Server data | Any | React Query / SWR |
| URL state | Navigation | useSearchParams / router |
React Query Patterns
- Configure a single
QueryClientat the app root withQueryClientProvider - Define query keys as constants or factory functions — never inline strings:
export const userKeys = { all: ['users'] as const, detail: (id: string) => ['users', id] as const, } - Use
suspense: truemode with<Suspense>boundaries for cleaner loading state handling - Mutations must call
queryClient.invalidateQuerieson success to keep cache coherent - Set
staleTimeexplicitly; default0causes unnecessary refetches
Context API
- Never put frequently-changing values (e.g., mouse position, scroll position) in context — it re-renders every consumer
- Split contexts by concern:
AuthContext,ThemeContext,NotificationContextare separate - Always provide a default value or throw a helpful error from the hook:
export function useAuth() { const ctx = useContext(AuthContext) if (!ctx) throw new Error('useAuth must be used inside AuthProvider') return ctx }
Concurrent Features
- Use
useTransitionto mark non-urgent state updates (search filtering, tab switching) so they don't block input responsiveness - Use
useDeferredValueto defer expensive derived computations from fast-changing inputs - Use
startTransitionfor route-level navigation transitions
Virtualization
- Use
@tanstack/react-virtualorreact-windowfor lists exceeding 100 items - Always provide
estimateSizeas accurately as possible to avoid layout thrash - Dynamic height virtualization requires
measureElementcallback — do not approximate
Security Requirements
- Never render raw HTML from user-supplied or API-supplied strings without explicit sanitization (
DOMPurify.sanitize()).dangerouslySetInnerHTMLis banned without sanitization. - Never store sensitive tokens (JWT, API keys) in component state or
localStoragewithout understanding the XSS exposure. PreferhttpOnlycookies for auth tokens. - Validate all form inputs both client-side (Zod,
react-hook-formresolvers) and server-side. - Avoid
eval()and dynamicimport()from user-controlled strings. - When rendering external URLs, validate protocol (
https:only) before using inhreforsrc.
Testing and Validation
Testing Library Rules
- Query priority (highest to lowest):
getByRole→getByLabelText→getByPlaceholderText→getByText→getByTestId - Never use
getByTestIdas a primary query — it tests implementation, not behavior - Use
screen.debug()only during development; remove before commit - Async rendering: always
awaitwithfindBy*queries orwaitFor(() => ...), never use arbitrarysetTimeout
Test Structure
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
describe('ComponentName', () => {
it('renders the primary action button', () => {
render(<ComponentName />)
expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument()
})
it('calls onSubmit when form is valid', async () => {
const user = userEvent.setup()
const onSubmit = vi.fn()
render(<ComponentName onSubmit={onSubmit} />)
await user.type(screen.getByLabelText(/email/i), '[email protected]')
await user.click(screen.getByRole('button', { name: /submit/i }))
expect(onSubmit).toHaveBeenCalledWith({ email: '[email protected]' })
})
})
Performance Validation
- Use React DevTools Profiler to baseline render times before optimizing
- Run
why-did-you-renderin development to catch unnecessary re-renders - Confirm Lighthouse Performance score stays above 90 for page-level components
Deliverables
- Component file(s) with TypeScript interfaces
- Custom hook file(s) if logic was extracted
- Test file(s) with ≥80% branch coverage on new code
- Updated exports in
index.tsbarrel files - Storybook story file if the project uses Storybook
Failure Handling
- Infinite render loop: caused by missing or incorrect
useEffectdeps, or object literals in JSX creating new references each render. Use the ESLintreact-hooks/exhaustive-depsrule anduseMemo/useCallbackto stabilize. - Stale closure: a function inside
useEffectcaptures an old value. Fix: add the value to the dependency array, or useuseRefto hold the latest version. - Context performance regression: if adding a context causes widespread re-renders, split the context or use a state manager with selector support (Zustand
useStore(state => state.x)). - Hydration mismatch (SSR): ensure server and client render identical output on first paint. Never use
Math.random(),Date.now(), or browser-only APIs withoutuseEffectguards. - Memory leak: every subscription, interval, or event listener set up in
useEffectmust be torn down in its cleanup return.
References
- React Docs (react.dev): hooks reference, Suspense, concurrent features
- TanStack Query docs:
@tanstack/react-queryv5 query keys, mutations, caching - Testing Library docs: query priority,
userEventv14 API - Zustand docs: slices pattern, middleware
react-error-boundarypackage:ErrorBoundary,useErrorBoundary- ESLint plugin:
eslint-plugin-react-hooks @tanstack/react-virtualdocs: virtual list implementation