CommunityProgramación y desarrollogithub.com

react-development

Shows an agent how to design, debug, or review "react development" so the concrete output is usable copy or a script. The procedure moves through React Development, Purpose, When to Activate. Use it when a new assignment calls for this craft.

¿Qué es react-development?

react-development is a Claude Code agent skill that shows an agent how to design, debug, or review "react development" so the concrete output is usable copy or a script. The procedure moves through React Development, Purpose, When to Activate. Use it when a new assignment calls for this craft.

Compatible con~Claude Code~Codex CLI~Cursor
Part ofReact
npx skills add https://github.com/lacklustr-coder/universal-ai-skills/tree/HEAD/skills/frontend/react-development

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

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

  1. 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.

  2. Define the prop interface first using TypeScript. Use interface for component props (extendable), type for unions and computed prop shapes. Mark optional props explicitly with ?. Never use any.

  3. Choose the right state primitive:

    • useState for simple local UI state (toggles, form inputs, counters)
    • useReducer when 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 in useState
  4. 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)
    
  5. Implement hooks following the Rules of Hooks strictly:

    • Only call hooks at the top level — no conditionals, no loops, no nested functions
    • Every useEffect must declare a complete dependency array; never suppress lint warnings without a documented reason
    • Cleanup side effects: return a cleanup function from every useEffect that sets up subscriptions, timers, or event listeners
    • Use useRef for values that must persist across renders without triggering re-renders (DOM refs, timer IDs, previous values)
  6. Implement memoization surgically, not by default:

    • React.memo on a component only when its parent re-renders frequently and its own props are stable
    • useMemo only for expensive computations (sort/filter of large arrays, complex derivations) — verify with profiler first
    • useCallback only when a callback is a dependency of another hook or passed to a memoized child
    • Premature memoization increases complexity without benefit; profile first
  7. Add error boundaries at logical subtree roots. Use a class component or the react-error-boundary library (ErrorBoundary + useErrorBoundary). Provide a fallback prop with a meaningful recovery UI, not just "Something went wrong."

  8. 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.

  9. Write tests using @testing-library/react. Every component gets at minimum: render test, interaction test (user events), and async state test where applicable. Use userEvent over fireEvent for realistic interaction simulation.

  10. 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, hasIcon on 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 useMemo if 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 renderHook from @testing-library/react

State Management Decision Matrix

ScopeComplexityTool
Single componentLowuseState
Single componentHighuseReducer
SubtreeAnyReact Context + useReducer
App-wide UI stateMediumZustand
App-wide fine-grainedHighJotai
Server dataAnyReact Query / SWR
URL stateNavigationuseSearchParams / router

React Query Patterns

  • Configure a single QueryClient at the app root with QueryClientProvider
  • 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: true mode with <Suspense> boundaries for cleaner loading state handling
  • Mutations must call queryClient.invalidateQueries on success to keep cache coherent
  • Set staleTime explicitly; default 0 causes 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, NotificationContext are 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 useTransition to mark non-urgent state updates (search filtering, tab switching) so they don't block input responsiveness
  • Use useDeferredValue to defer expensive derived computations from fast-changing inputs
  • Use startTransition for route-level navigation transitions

Virtualization

  • Use @tanstack/react-virtual or react-window for lists exceeding 100 items
  • Always provide estimateSize as accurately as possible to avoid layout thrash
  • Dynamic height virtualization requires measureElement callback — do not approximate

Security Requirements

  • Never render raw HTML from user-supplied or API-supplied strings without explicit sanitization (DOMPurify.sanitize()). dangerouslySetInnerHTML is banned without sanitization.
  • Never store sensitive tokens (JWT, API keys) in component state or localStorage without understanding the XSS exposure. Prefer httpOnly cookies for auth tokens.
  • Validate all form inputs both client-side (Zod, react-hook-form resolvers) and server-side.
  • Avoid eval() and dynamic import() from user-controlled strings.
  • When rendering external URLs, validate protocol (https: only) before using in href or src.

Testing and Validation

Testing Library Rules

  • Query priority (highest to lowest): getByRole → getByLabelText → getByPlaceholderText → getByText → getByTestId
  • Never use getByTestId as a primary query — it tests implementation, not behavior
  • Use screen.debug() only during development; remove before commit
  • Async rendering: always await with findBy* queries or waitFor(() => ...), never use arbitrary setTimeout

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-render in 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.ts barrel files
  • Storybook story file if the project uses Storybook

Failure Handling

  • Infinite render loop: caused by missing or incorrect useEffect deps, or object literals in JSX creating new references each render. Use the ESLint react-hooks/exhaustive-deps rule and useMemo/useCallback to stabilize.
  • Stale closure: a function inside useEffect captures an old value. Fix: add the value to the dependency array, or use useRef to 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 without useEffect guards.
  • Memory leak: every subscription, interval, or event listener set up in useEffect must be torn down in its cleanup return.

References

  • React Docs (react.dev): hooks reference, Suspense, concurrent features
  • TanStack Query docs: @tanstack/react-query v5 query keys, mutations, caching
  • Testing Library docs: query priority, userEvent v14 API
  • Zustand docs: slices pattern, middleware
  • react-error-boundary package: ErrorBoundary, useErrorBoundary
  • ESLint plugin: eslint-plugin-react-hooks
  • @tanstack/react-virtual docs: virtual list implementation

Skills relacionados