# React Standards

Extends `references/common/coding-standards.md` with React-specific conventions. Loaded at codify/harden phase — not active during prototype iteration.

## Imports

- Named imports only: `import { useState } from 'react'` — never `import React from 'react'`
- Group: react → third-party → local components → local utils → types
- Absolute imports via path aliases (`@/components/Button`) over deep relative paths

## Minimize useEffect

Most effects are unnecessary. See [React docs: You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect).

| You want to... | Use this instead |
|---|---|
| Derive/transform data from props/state | Compute during render (`useMemo` or variable) |
| Respond to a user event | Event handler (`onClick`, `onSubmit`) |
| Fetch data | React Query / SWR / loader |
| Reset state when props change | `key` prop (remount) |

**When useEffect IS appropriate:** synchronizing with external systems (WebSocket, DOM APIs, third-party widgets), subscriptions, non-React integrations.

**Rules when you must use it:** always specify deps array, one effect per concern, always clean up, never set derivable state, avoid effect chains.

## Component Patterns

- Functional components only — no class components
- Composition over inheritance
- Custom hooks (`use*`) for shared stateful logic
- Single responsibility — split at 200 lines
- Props interface for every component

## State Management

- Local state first (`useState`) → lift up only when siblings share → context for low-frequency global (theme, auth) → external store for complex state
- Avoid prop drilling > 2 levels — use composition or context
- Derive, don't sync — if B computes from A, compute it. Don't useEffect to sync.

## Performance

- `useMemo` for expensive computations, `useCallback` for callbacks to memoized children (only when needed)
- `React.memo` for components that render often with same props — profile first
- `React.lazy()` + `Suspense` for routes and heavy components
- Avoid anonymous objects/arrays in JSX props — extract to stable references

## Event Handling

- Handle events in event handlers, not effects
- Use `useActionState` or form actions (React 19+) for form submissions

## Data Fetching

- Use React Query, SWR, or framework loaders — never `useEffect` + `fetch` + `useState` in new code

## Testing

- Test behavior (what the user sees), not implementation (hook internals, state)
- React Testing Library — query by role, label, text; not className or testId
- "One behavior per test" = one user intent: a full form flow (fill → submit → verify) is ONE test
- Prefer `msw` for network mocks; render real child components
