---
name: react-best-practices
description: Modern React 19 patterns for components, hooks, state management, performance, and project structure. Use when writing React components, reviewing React code, designing component APIs, or when the user asks about React conventions, architecture, or best practices.
title: react-best-practices
canonical_url: https://skilld.dev/gh/grahamcrackers/skills/react-best-practices
last_updated: 2026-10-07T02:20:44.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install grahamcrackers/skills/react-best-practices`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/react-best-practices`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/grahamcrackers/skills/react-best-practices) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/react-best-practices`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/react-best-practices --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/react-best-practices --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# React Best Practices

## Component Design

- One component per file. Name the file the same as the component.
- Prefer function components — never write class components.
- Keep components small and focused. If a component exceeds ~150 lines, split it.
- Define components at module scope — never define components inside other components (breaks state preservation and identity).
- Colocate related files (component, hook, types, styles, tests) in the same directory.

## Props

- Destructure props in the function signature:

```tsx
function UserCard({ name, email, avatar }: UserCardProps) { ... }
```

- Use `children` via `React.PropsWithChildren` or explicit `children: React.ReactNode`.
- Prefer specific prop types over `Record<string, unknown>` or `any`.
- Avoid prop drilling beyond 2-3 levels — use composition, context, or a state management solution.

## Hooks

- Follow the Rules of Hooks: only call at the top level, only in React components or custom hooks.
- Extract reusable logic into custom hooks (`use*` prefix).
- Keep hooks focused — a hook that does too many things should be split.

### State Management

- Keep state as local as possible. Lift only when sibling components need it.
- Use `useReducer` for complex state with multiple related transitions.
- Reserve context for truly global concerns (theme, auth, locale) — not frequently changing data.
- For server state, use TanStack Query or a similar library instead of `useState` + `useEffect`.

### React 19 Hooks

- **`use()`**: Read context or unwrap promises inside components. Replaces some `useContext` patterns.
- **`useActionState()`**: Manage form submission state (pending, error, result) without manual boilerplate.
- **`useOptimistic()`**: Show optimistic UI immediately during async operations.
- **`useTransition()`**: Wrap non-urgent state updates to keep the UI responsive.

## React 19 Patterns

### Automatic Memoization (React Compiler)

When using the React Compiler:

- Remove manual `React.memo()`, `useMemo()`, and `useCallback()` — the compiler handles memoization automatically.
- If not using the compiler, still be intentional — only memoize when profiling reveals a real performance issue.

### Actions and Forms

Use React 19 Actions for form handling:

```tsx
function CreatePost() {
    const [state, action, isPending] = useActionState(createPostAction, null);

    return (
        <form action={action}>
            <input name="title" required />
            <button type="submit" disabled={isPending}>
                Create
            </button>
            {state?.error && <p>{state.error}</p>}
        </form>
    );
}
```

### Server Components

- Default to server components for non-interactive content (data display, lists, static layouts).
- Add `"use client"` only when the component needs interactivity (event handlers, hooks, browser APIs).
- Push `"use client"` boundaries as far down the tree as possible.

## Performance

- Use `React.lazy()` + `Suspense` for code-splitting large routes and heavy components.
- Use `startTransition` for expensive state updates that don't need immediate rendering.
- Wrap `Suspense` boundaries around async data fetching to avoid waterfall loading.
- Avoid creating new objects/arrays in JSX props on every render — extract to constants or memoize.

## Patterns

### Composition over Configuration

Prefer composable children over giant config props:

```tsx
// Prefer
<Dialog>
  <Dialog.Header>Title</Dialog.Header>
  <Dialog.Body>Content</Dialog.Body>
  <Dialog.Footer>
    <Button>Close</Button>
  </Dialog.Footer>
</Dialog>

// Avoid
<Dialog
  header="Title"
  body="Content"
  footer={<Button>Close</Button>}
/>
```

### Render Props & Children as Function

Use when a component needs to share render-time data without prescribing UI:

```tsx
<DataLoader query={userQuery}>{(data) => <UserProfile user={data} />}</DataLoader>
```

### Custom Hook + Component Pairs

Separate logic from presentation:

```tsx
function useUserSearch(query: string) {
    // filtering, debouncing, API calls
    return { results, isLoading, error };
}

function UserSearch() {
    const [query, setQuery] = useState("");
    const { results, isLoading } = useUserSearch(query);
    // render
}
```

## Error Handling

- Use Error Boundaries to catch render errors and show fallback UI.
- Don't use Error Boundaries for event handler errors — use try/catch in the handler.
- Provide meaningful fallback UI, not blank screens.

## Testing

- Test behavior, not implementation. Query by role, label, or text — not by test IDs or CSS classes.
- Use `@testing-library/react` for component tests.
- Mock at the network boundary (e.g., MSW) rather than mocking hooks or internal state.
- Test custom hooks with `renderHook` from `@testing-library/react`.

## Project Structure

```
src/
├── components/       # shared/reusable components
│   └── button/
│       ├── button.tsx
│       ├── button.test.tsx
│       └── index.ts
├── features/         # feature-specific code (components, hooks, utils)
│   └── auth/
├── hooks/            # shared custom hooks
├── lib/              # utilities, API clients, helpers
├── types/            # shared TypeScript types
└── app/              # routes / pages
```

Colocate feature-specific code in `features/` and only promote to `components/` or `hooks/` when reused across features.
