React Cursor Rules: JSX, Hooks, and Component Patterns

Comprehensive React cursor rules covering component architecture, JSX patterns, hooks usage, accessibility, and testing for maintainable, performant applications.

November 14, 2025by PromptGenius Team
reactcursor-rulesfrontendjsxhooks

Overview

Professional cursor rules for React that emphasize modern component architecture, hooks, and JSX. These rules help AI assistants generate clean, accessible, and maintainable React code with complete context and effective patterns.

Note:

Optimizes React 18+ patterns, hooks, and JSX with context-aware code generation aligned to modern best practices.

Rules Configuration

---
description: Enforces best practices for React development, focusing on context-aware code generation, component architecture, hooks usage, and JSX patterns. Provides comprehensive guidelines for writing clean, efficient, and maintainable React code with proper context.
globs: **/*.{js,jsx,ts,tsx}
---
# React Best Practices

You are an expert in React 18+ development and related web technologies.
You understand modern React practices, architectural patterns, and the importance of providing complete context in code generation.

### Context-Aware Code Generation
- Always provide complete component context including imports, props interface, and state shape
- Include relevant configuration files (tsconfig.json, package.json) when generating components
- Generate complete component signatures with proper TypeScript props and return types
- Include comprehensive documentation for component purpose, props, and side effects
- Provide context about the component's role in the larger application architecture

### Component Architecture
- Use functional components with hooks over class components
- Keep components focused on a single responsibility
- Use composition over inheritance for component reuse
- Extract reusable logic into custom hooks
- Use React.memo strategically for components that render often with the same props

### Hooks Best Practices
- Use useState for local component state
- Use useReducer for complex state logic with multiple sub-values
- Use useEffect with proper dependency arrays; avoid missing dependencies
- Use useCallback and useMemo only when profiling shows a measurable benefit
- Use useRef for DOM references and mutable values that don't trigger re-renders
- Use useContext for shared state that doesn't change frequently

### Performance
- Memoize components and values where profiling shows benefit
- Split code by route and feature boundaries using React.lazy and Suspense
- Defer non-critical work with startTransition and useDeferredValue
- Avoid unnecessary re-renders by keeping state as close to where it's used
- Profile with React DevTools before optimizing

### Testing & Quality
- Write unit tests with React Testing Library and Jest
- Test user interactions with fireEvent and userEvent
- Use screen queries (getByRole, findByText) over component internals
- Mock external API calls with MSW for reliable integration tests
- Measure coverage for core feature flows

### Accessibility
- Use semantic HTML elements (button, nav, main) over generic divs
- Add aria-* attributes for custom interactive components
- Ensure keyboard navigation for all interactive elements
- Test with screen readers and axe-core for accessibility compliance

Examples

// components/Counter.tsx — Functional component with hooks
import { useState, useCallback } from 'react'

interface CounterProps {
  initialCount?: number
  label?: string
}

export function Counter({ initialCount = 0, label = 'Count' }: CounterProps) {
  const [count, setCount] = useState(initialCount)

  const increment = useCallback(() => setCount(prev => prev + 1), [])
  const decrement = useCallback(() => setCount(prev => prev - 1), [])

  return (
    <div role="group" aria-label={label}>
      <p aria-live="polite">{label}: {count}</p>
      <button onClick={increment} aria-label="Increment">+</button>
      <button onClick={decrement} aria-label="Decrement">-</button>
    </div>
  )
}
// hooks/useFetch.ts — Custom hook for data fetching
import { useState, useEffect } from 'react'

interface FetchState<T> {
  data: T | null
  loading: boolean
  error: Error | null
}

export function useFetch<T>(url: string): FetchState<T> {
  const [state, setState] = useState<FetchState<T>>({
    data: null,
    loading: true,
    error: null,
  })

  useEffect(() => {
    let cancelled = false
    setState(prev => ({ ...prev, loading: true }))

    fetch(url)
      .then(res => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        return res.json()
      })
      .then(data => {
        if (!cancelled) setState({ data, loading: false, error: null })
      })
      .catch(error => {
        if (!cancelled) setState({ data: null, loading: false, error })
      })

    return () => { cancelled = true }
  }, [url])

  return state
}
🎣

Hooks Intelligence

Dependency awareness for effects, state patterns, and cleanup

📘

Type Safety

Interface and prop validation for TS and JS projects

🧪

Testing Built-In

Generate tests with React Testing Library and Jest

Accessibility

ARIA roles, keyboard navigation, and semantic HTML

Performance

Memoization, code splitting, and lazy loading patterns

🧩

Component Composition

Compound components and context-driven patterns

Installation

1

Choose Your IDE

Select the appropriate file path based on your development environment.

2

Create the Rules File

Create the cursor rules file in your project using the tabs above.

3

Add the Rules Configuration

Copy the configuration markdown into the file.

4

Start Building

Your AI assistant will follow React best practices automatically.

Use Cases

Component Libraries

Reusable UI components with clear props and stories

React Applications

Feature-rich apps with state management and routing

Next.js Full-Stack

Server-first apps with hybrid rendering strategies

Design Systems

Consistent UI with tokens, themes, and accessibility

Standards Reference

StandardDescriptionEnforcement
React 18Modern component and hook patternsRequired in all code
JSXDeclarative UI syntaxEnforced via structure
HooksState and side-effect managementDependency awareness
TestingRTL/Jest coverageAuto-generated with code
AccessibilityARIA and semantic HTMLBuilt into patterns
ArchitectureComposition and separation of concernsEnforced via structure

Note:

Combine these rules with TypeScript and ESLint for maximum code quality.

Best Practices

Code Organization

  • Components expose clear props
  • Context providers manage shared state
  • Utilities and hooks encapsulate logic
  • Pages compose features and layouts

State Management

  • Prefer local state for UI concerns
  • Use context for cross-cutting state
  • Apply reducers for complex state transitions
  • Keep effects focused and dependency-safe

Performance

  • Memoize components and values where beneficial
  • Split code by route and feature boundaries
  • Defer non-critical work and lazy load assets
  • Avoid unnecessary re-renders

Testing Strategy

  • Unit tests for components and hooks
  • Integration tests for user flows
  • Mock external dependencies appropriately
  • Measure coverage for core features

Note:

These rules work with any React project and pair well with Next.js. Adjust framework-specific sections as needed.