React Development Guide
This skill provides comprehensive guidelines, patterns, and best practices for React development in this project.
Quick Start
- Best Practices: For component architecture, state management, and TypeScript integration, read
references/best-practices.md
- Element wrappers: If a component renders a single native element (
button, input, a, …), extend that element’s props (React.ComponentProps<"…">) and spread ...props — see Extend native element props below and references/best-practices.md → Extending HTML Elements.
- useEffect Patterns: For understanding when to use (and avoid) useEffect, read
references/useeffect-patterns.md
- Data Fetching: For TanStack Query patterns, use the
tanstack skill
- Forms: For form handling with TanStack Form, use the
tanstack skill
Core Principles
- Functional Components Only: Use functional components exclusively - class components are legacy
- Single Responsibility: Keep components small and focused on a single purpose
- Separation of Concerns: Extract behavior logic into custom hooks, keep components focused on rendering
- Feature-Based Organization: Co-locate related files by feature, not by type
- React 19+ Features: Embrace modern React features (
use(), Actions, useOptimistic())
Extend native element props
Default rule for wrappers: whenever a component’s root output is a single native element, its props interface MUST extend that element’s intrinsic props — same contract as shadcn/ui-generated primitives. Callers keep access to aria-*, data-*, onClick, disabled, etc., without bespoke passthrough lists.
Do this:
| Requirement |
Detail |
| Base type |
interface XProps extends React.ComponentProps<"button"> (or "input", "a", "div", …) |
| Spreading |
Destructure your custom fields, then {...props} (and merged className) onto the DOM node |
| Ref |
Use React.forwardRef and the matching element ref type when refs are needed |
interface TextFieldProps extends React.ComponentProps<"input"> {
label: string;
error?: string;
}
function TextField({ label, error, className, ...props }: TextFieldProps) {
return (
<label className="flex flex-col gap-1">
<span>{label}</span>
<input className={cn("rounded border px-2 py-1", error && "border-destructive", className)} {...props} />
{error ? <span className="text-destructive text-sm">{error}</span> : null}
</label>
);
}
Variants + CVA: if you use class-variance-authority, combine intrinsic props with VariantProps<typeof variants> (often extends React.ButtonHTMLAttributes<HTMLButtonElement>). Follow the shadcn skill patterns.
Deep dive: references/best-practices.md → Extending HTML Elements.
Quick Reference Tables
State Management Hierarchy
| Priority |
Tool |
Use Case |
| 1 |
useState/useReducer |
Component-specific UI state |
| 2 |
Zustand |
Shared client state across components |
| 3 |
TanStack Query |
Server state and data synchronization |
| 4 |
URL state |
Shareable application state (TanStack Router) |
useEffect Decision Tree
| Situation |
DON'T |
DO |
| Derived state from props/state |
useState + useEffect |
Calculate during render |
| Expensive calculations |
useEffect to cache |
useMemo |
| Reset state on prop change |
useEffect with setState |
key prop |
| User event responses |
useEffect watching state |
Event handler directly |
| Notify parent of changes |
useEffect calling onChange |
Call in event handler |
| Fetch data |
useEffect without cleanup |
useEffect with cleanup OR TanStack Query |
When You DO Need Effects
- Synchronizing with external systems (non-React widgets, browser APIs)
- Subscriptions to external stores (use
useSyncExternalStore when possible)
- Analytics/logging that runs because component displayed
- Data fetching with proper cleanup (or use TanStack Query)
When You DON'T Need Effects
- Transforming data for rendering - Calculate at top level, re-runs automatically
- Handling user events - Use event handlers, you know exactly what happened
- Deriving state - Just compute it:
const fullName = firstName + ' ' + lastName
- Chaining state updates - Calculate all next state in the event handler
TypeScript Integration
// CORRECT: Type props directly (never use React.FC)
interface BrandButtonProps {
variant: "primary" | "secondary";
children: React.ReactNode;
}
function BrandButton({ variant, children }: BrandButtonProps) {
return <button type="button" className={variant}>{children}</button>;
}
// When wrapping a native element, extend its props — see "Extend native element props" above
interface IconButtonProps extends React.ComponentProps<"button"> {
icon: React.ReactNode;
}
Custom Hooks Guidelines
- Extract non-visual logic into custom hooks
- Keep hooks focused on single purpose
- Use clear naming:
useXxx pattern
- Return arrays for state-like hooks, objects for complex returns
// State-like hook returns array
function useToggle(initial = false) {
const [value, setValue] = useState(initial);
const toggle = useCallback(() => setValue((v) => !v), []);
return [value, toggle] as const;
}
// Complex hook returns object
function useUser(id: string) {
const query = useQuery({ queryKey: ["user", id], queryFn: () => fetchUser(id) });
return {
user: query.data,
isLoading: query.isLoading,
error: query.error,
refetch: query.refetch,
};
}
Component Architecture Pattern
// CORRECT: Hook handles all logic, component handles rendering
function useIssueSearch(projectId: string) {
const [query, setQuery] = useState("");
const [filters, setFilters] = useState<Filters>({});
const issues = useQuery({
queryKey: ["issues", projectId, query, filters],
queryFn: () => searchIssues(projectId, query, filters),
});
return {
query,
setQuery,
filters,
setFilters,
issues: issues.data ?? [],
isLoading: issues.isLoading,
};
}
function IssueList({ projectId }: { projectId: string }) {
const { query, setQuery, issues, isLoading } = useIssueSearch(projectId);
return (
<div>
<SearchInput value={query} />
{isLoading ? <Loading /> : <IssueTable issues={issues} />}
</div>
);
}
File Naming Conventions
| Type |
Pattern |
Example |
| Components |
kebab-case.tsx |
user-avatar.tsx |
| Hooks |
use-kebab-case.ts |
use-user-data.ts |
| Utilities |
camelCase.ts |
formatDate.ts |
| Types |
types.ts |
types.ts |
| Tests |
*.test.tsx |
user-avatar.test.tsx |
Testing with Vitest
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { renderHook, act } from "@testing-library/react";
describe("MyComponent", () => {
it("renders correctly", () => {
render(<MyComponent />);
expect(screen.getByText("Hello")).toBeInTheDocument();
});
});
describe("useMyHook", () => {
it("returns expected value", () => {
const { result } = renderHook(() => useMyHook());
expect(result.current.value).toBe(expected);
});
});
Validation Checklist
Before finishing a task involving React:
Detailed References
For comprehensive guidance, consult these reference files:
references/best-practices.md - Component architecture, TypeScript, state management, React 19+ features, testing patterns
references/useeffect-patterns.md - When to use/avoid useEffect, anti-patterns, and better alternatives
1---2name: react3description: Comprehensive React development guide covering component architecture, hooks, state management, TypeScript integration, useEffect patterns, and testing with Vitest. Use when creating React components, custom hooks, managing state, or any frontend React code. Essential for React 19+ development. Don't use for React Native, non-React frameworks (Vue, Svelte, Solid), or backend-only Node.js code.4---5# React Development Guide67This skill provides comprehensive guidelines, patterns, and best practices for React development in this project.89## Quick Start10111. **Best Practices**: For component architecture, state management, and TypeScript integration, read `references/best-practices.md`122. **Element wrappers**: If a component renders a single native element (`button`, `input`, `a`, …), extend that element’s props (`React.ComponentProps<"…">`) and spread `...props` — see **Extend native element props** below and `references/best-practices.md` → *Extending HTML Elements*.133. **useEffect Patterns**: For understanding when to use (and avoid) useEffect, read `references/useeffect-patterns.md`144. **Data Fetching**: For TanStack Query patterns, use the `tanstack` skill155. **Forms**: For form handling with TanStack Form, use the `tanstack` skill1617## Core Principles1819- **Functional Components Only**: Use functional components exclusively - class components are legacy20- **Single Responsibility**: Keep components small and focused on a single purpose21- **Separation of Concerns**: Extract behavior logic into custom hooks, keep components focused on rendering22- **Feature-Based Organization**: Co-locate related files by feature, not by type23- **React 19+ Features**: Embrace modern React features (`use()`, Actions, `useOptimistic()`)2425## Extend native element props2627**Default rule for wrappers:** whenever a component’s root output is a **single native element**, its props interface MUST extend that element’s intrinsic props — same contract as shadcn/ui-generated primitives. Callers keep access to `aria-*`, `data-*`, `onClick`, `disabled`, etc., without bespoke passthrough lists.2829**Do this:**3031| Requirement | Detail |32| ------------- | ------ |33| Base type | `interface XProps extends React.ComponentProps<"button">` (or `"input"`, `"a"`, `"div"`, …) |34| Spreading | Destructure your custom fields, then `{...props}` (and merged `className`) onto the DOM node |35| Ref | Use `React.forwardRef` and the matching element ref type when refs are needed |3637```typescript38interface TextFieldProps extends React.ComponentProps<"input"> {39 label: string;40 error?: string;41}4243function TextField({ label, error, className, ...props }: TextFieldProps) {44 return (45 <label className="flex flex-col gap-1">46 <span>{label}</span>47 <input className={cn("rounded border px-2 py-1", error && "border-destructive", className)} {...props} />48 {error ? <span className="text-destructive text-sm">{error}</span> : null}49 </label>50 );51}52```5354**Variants + CVA:** if you use `class-variance-authority`, combine intrinsic props with `VariantProps<typeof variants>` (often `extends React.ButtonHTMLAttributes<HTMLButtonElement>`). Follow the **`shadcn`** skill patterns.5556**Deep dive:** `references/best-practices.md` → *Extending HTML Elements*.5758## Quick Reference Tables5960### State Management Hierarchy6162| Priority | Tool | Use Case |63|----------|------|----------|64| 1 | `useState`/`useReducer` | Component-specific UI state |65| 2 | Zustand | Shared client state across components |66| 3 | TanStack Query | Server state and data synchronization |67| 4 | URL state | Shareable application state (TanStack Router) |6869### useEffect Decision Tree7071| Situation | DON'T | DO |72|-----------|-------|-----|73| Derived state from props/state | `useState` + `useEffect` | Calculate during render |74| Expensive calculations | `useEffect` to cache | `useMemo` |75| Reset state on prop change | `useEffect` with `setState` | `key` prop |76| User event responses | `useEffect` watching state | Event handler directly |77| Notify parent of changes | `useEffect` calling `onChange` | Call in event handler |78| Fetch data | `useEffect` without cleanup | `useEffect` with cleanup OR TanStack Query |7980### When You DO Need Effects8182- Synchronizing with **external systems** (non-React widgets, browser APIs)83- **Subscriptions** to external stores (use `useSyncExternalStore` when possible)84- **Analytics/logging** that runs because component displayed85- **Data fetching** with proper cleanup (or use TanStack Query)8687### When You DON'T Need Effects88891. **Transforming data for rendering** - Calculate at top level, re-runs automatically902. **Handling user events** - Use event handlers, you know exactly what happened913. **Deriving state** - Just compute it: `const fullName = firstName + ' ' + lastName`924. **Chaining state updates** - Calculate all next state in the event handler9394## TypeScript Integration9596```typescript97// CORRECT: Type props directly (never use React.FC)98interface BrandButtonProps {99 variant: "primary" | "secondary";100 children: React.ReactNode;101}102103function BrandButton({ variant, children }: BrandButtonProps) {104 return <button type="button" className={variant}>{children}</button>;105}106107// When wrapping a native element, extend its props — see "Extend native element props" above108interface IconButtonProps extends React.ComponentProps<"button"> {109 icon: React.ReactNode;110}111```112113## Custom Hooks Guidelines114115- Extract non-visual logic into custom hooks116- Keep hooks focused on single purpose117- Use clear naming: `useXxx` pattern118- Return arrays for state-like hooks, objects for complex returns119120```typescript121// State-like hook returns array122function useToggle(initial = false) {123 const [value, setValue] = useState(initial);124 const toggle = useCallback(() => setValue((v) => !v), []);125 return [value, toggle] as const;126}127128// Complex hook returns object129function useUser(id: string) {130 const query = useQuery({ queryKey: ["user", id], queryFn: () => fetchUser(id) });131 return {132 user: query.data,133 isLoading: query.isLoading,134 error: query.error,135 refetch: query.refetch,136 };137}138```139140## Component Architecture Pattern141142```typescript143// CORRECT: Hook handles all logic, component handles rendering144function useIssueSearch(projectId: string) {145 const [query, setQuery] = useState("");146 const [filters, setFilters] = useState<Filters>({});147148 const issues = useQuery({149 queryKey: ["issues", projectId, query, filters],150 queryFn: () => searchIssues(projectId, query, filters),151 });152153 return {154 query,155 setQuery,156 filters,157 setFilters,158 issues: issues.data ?? [],159 isLoading: issues.isLoading,160 };161}162163function IssueList({ projectId }: { projectId: string }) {164 const { query, setQuery, issues, isLoading } = useIssueSearch(projectId);165166 return (167 <div>168 <SearchInput value={query} onChange={setQuery} />169 {isLoading ? <Loading /> : <IssueTable issues={issues} />}170 </div>171 );172}173```174175## File Naming Conventions176177| Type | Pattern | Example |178|------|---------|---------|179| Components | kebab-case.tsx | `user-avatar.tsx` |180| Hooks | use-kebab-case.ts | `use-user-data.ts` |181| Utilities | camelCase.ts | `formatDate.ts` |182| Types | types.ts | `types.ts` |183| Tests | *.test.tsx | `user-avatar.test.tsx` |184185## Testing with Vitest186187```typescript188import { describe, it, expect, vi } from "vitest";189import { render, screen } from "@testing-library/react";190import { renderHook, act } from "@testing-library/react";191192describe("MyComponent", () => {193 it("renders correctly", () => {194 render(<MyComponent />);195 expect(screen.getByText("Hello")).toBeInTheDocument();196 });197});198199describe("useMyHook", () => {200 it("returns expected value", () => {201 const { result } = renderHook(() => useMyHook());202 expect(result.current.value).toBe(expected);203 });204});205```206207## Validation Checklist208209Before finishing a task involving React:210211- [ ] Components are functional and follow single responsibility principle212- [ ] Behavior logic is extracted into custom hooks213- [ ] TypeScript props are typed directly (not using `React.FC`); native wrappers extend `React.ComponentProps<"…">` (or `ButtonHTMLAttributes` + variants per `shadcn` skill) and forward `...props`214- [ ] State management follows the hierarchy (local -> Zustand -> TanStack Query -> URL)215- [ ] useEffect is only used for external system synchronization216- [ ] Error boundaries are in place for error handling217- [ ] Loading and error states are handled218- [ ] Accessibility requirements are met (semantic HTML, keyboard navigation)219- [ ] Tests are written for components and hooks220- [ ] Run `pnpm run lint`, `pnpm run typecheck`, and `pnpm run test`221222## Detailed References223224For comprehensive guidance, consult these reference files:225226- `references/best-practices.md` - Component architecture, TypeScript, state management, React 19+ features, testing patterns227- `references/useeffect-patterns.md` - When to use/avoid useEffect, anti-patterns, and better alternatives