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.
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
Choose Your IDE
Select the appropriate file path based on your development environment.
Create the Rules File
Create the cursor rules file in your project using the tabs above.
Add the Rules Configuration
Copy the configuration markdown into the file.
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
| Standard | Description | Enforcement |
|---|---|---|
| React 18 | Modern component and hook patterns | Required in all code |
| JSX | Declarative UI syntax | Enforced via structure |
| Hooks | State and side-effect management | Dependency awareness |
| Testing | RTL/Jest coverage | Auto-generated with code |
| Accessibility | ARIA and semantic HTML | Built into patterns |
| Architecture | Composition and separation of concerns | Enforced 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
Related Resources
- Frontend framework cursor rules overview
- Next.js cursor rules for server-first apps
- TypeScript cursor rules for strict typing
- JavaScript cursor rules for modern ES features
- General cursor rules best practices and patterns
Note:
These rules work with any React project and pair well with Next.js. Adjust framework-specific sections as needed.
Related Articles
AI Rule Best Practices: Configure, Manage, and Optimize
Master AI rule configuration for development. Learn best practices to implement, manage, and optimize AI rules, ensuring code quality, consistency, and enhanced developer workflows.
AI Rules in Modern IDEs: Global and Project-Specific Configurations
AI rules customize AI assistants in modern IDEs like Cursor, Windsurf, and VSCode Copilot. Learn to configure global and project-specific rules for consistent, high-quality code.
Frontend Framework Cursor Rules for Modern Web Development
Master cursor rules for React, Vue, Angular, Next.js, Svelte, Qwik, and Astro. Framework-specific best practices for efficient web development workflows.