# React development patterns (React 19.2)

> Verified 2026-09 against react.dev and nextjs.org. Long-form samples referenced from `SKILL.md`.

## 1. Component template

```tsx
import type { ComponentPropsWithoutRef } from 'react';
import { formatMoney } from '@/shared/lib/money';
import type { Order } from '../model/order';

export type OrderRowProps = {
  order: Order;
  selected?: boolean;
  onSelect: (id: Order['id']) => void;
} & Omit<ComponentPropsWithoutRef<'li'>, 'onSelect'>;

export function OrderRow({ order, selected = false, onSelect, ...rest }: OrderRowProps) {
  const total = formatMoney(order.total, order.currency); // derived in render, never stored

  return (
    <li aria-selected={selected} {...rest}>
      <button type="button" onClick={() => onSelect(order.id)} aria-label={`Open order ${order.number}`}>
        <span>{order.number}</span>
        <span>{total}</span>
      </button>
    </li>
  );
}
```

`ref` as a prop (React 19.0+): `ComponentProps<'input'>` already includes `ref`, so a wrapper is just

```tsx
import type { ComponentProps } from 'react';

export function TextInput(props: ComponentProps<'input'>) {
  return <input className="input" {...props} />;
}
// parent: const ref = useRef<HTMLInputElement>(null); <TextInput ref={ref} />; ref.current?.focus();
```

## 2. `useEffect` — what to use instead

| You want to… | Use instead |
|---|---|
| Compute something from props/state | Derive in render (the compiler memoises); `useMemo` only when the lint rule shows a bail-out and it is measurably slow |
| Reset state when a prop changes | `key` on the component, or derive |
| Respond to a user event | The event handler |
| Fetch data | TanStack Query / route `loader` / async Server Component |
| Notify the parent of a change | Call `onChange` in the handler |
| Subscribe to an external store | `useSyncExternalStore` |
| Read the latest prop inside an effect without re-running it | `useEffectEvent` (19.2+) |
| Sync with a browser API, widget, socket or timer | **`useEffect`** with a cleanup — this is what it is for |

Source: https://react.dev/learn/you-might-not-need-an-effect

## 3. `use()` — context and promises

```tsx
import { use, Suspense } from 'react';
import { ThemeContext } from '@/shared/theme';

function Divider({ show }: { show: boolean }) {
  if (!show) return null;
  const theme = use(ThemeContext); // allowed after an early return; useContext is not
  return <hr className={theme} />;
}

// Streaming from a Server Component (Next.js): pass the promise, read it in a client component
export function Comments({ commentsPromise }: { commentsPromise: Promise<Comment[]> }) {
  const comments = use(commentsPromise); // suspends; the parent renders <Suspense fallback=…>
  return <ul>{comments.map(c => <li key={c.id}>{c.text}</li>)}</ul>;
}
```

`use` cannot be called inside `try/catch`; wrap the tree in an error boundary. https://react.dev/reference/react/use

## 4. Server Action form with `useActionState` (Next.js 16)

```ts
// features/profile/api/actions.ts
'use server';
import { updateTag } from 'next/cache';
import { z } from 'zod';
import { db } from '@/server/db';

const ProfileSchema = z.object({ name: z.string().min(1), email: z.string().email() });
export type ProfileState = { errors?: Partial<Record<'name' | 'email', string[]>>; ok?: boolean };

export async function saveProfile(userId: string, _prev: ProfileState, formData: FormData): Promise<ProfileState> {
  const parsed = ProfileSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors };
  await db.users.update(userId, parsed.data);
  updateTag(`user-${userId}`); // read-your-writes: the next render sees the change
  return { ok: true };
}
```

```tsx
// features/profile/components/ProfileForm.tsx
'use client';
import { useActionState } from 'react';
import { saveProfile, type ProfileState } from '../api/actions';

export function ProfileForm({ userId }: { userId: string }) {
  const [state, action, pending] = useActionState<ProfileState, FormData>(saveProfile.bind(null, userId), {});
  return (
    <form action={action}>
      <label htmlFor="name">Name</label>
      <input id="name" name="name" aria-invalid={!!state.errors?.name} aria-describedby="name-error" />
      {state.errors?.name && <p id="name-error" role="alert">{state.errors.name[0]}</p>}
      <button type="submit" disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
    </form>
  );
}
```

Outside a Server Action (route handlers, webhooks) use `revalidateTag(tag, 'max')`; the single-argument form is deprecated in Next.js 16. https://nextjs.org/blog/next-16

## 5. `<Activity>` — keep hidden UI mounted (React 19.2)

```tsx
import { Activity, useState } from 'react';

export function Workspace() {
  const [tab, setTab] = useState<'editor' | 'preview'>('editor');
  return (
    <>
      <Activity mode={tab === 'editor' ? 'visible' : 'hidden'}><Editor /></Activity>
      <Activity mode={tab === 'preview' ? 'visible' : 'hidden'}><Preview /></Activity>
    </>
  );
}
```

Hidden activities keep state, render at low priority and have their effects cleaned up; visible again restores state and re-creates effects. https://react.dev/reference/react/Activity

## 6. `<ViewTransition>` — canary only

Available on the React canary channel (Next.js 16 App Router ships it); not in a stable 19.x release yet. Wrap the element and drive the update through `startTransition`:

```tsx
import { ViewTransition, startTransition, useState } from 'react';

function Item() {
  return <ViewTransition enter="auto" exit="auto" default="none"><div>Hi</div></ViewTransition>;
}
export function Parent() {
  const [show, setShow] = useState(false);
  return (
    <>
      <button onClick={() => startTransition(() => setShow(s => !s))}>Toggle</button>
      {show ? <Item /> : null}
    </>
  );
}
```

On stable React use CSS transitions or the `motion` library. https://react.dev/reference/react/ViewTransition

## 7. Error boundaries

```tsx
import { ErrorBoundary } from 'react-error-boundary';

<ErrorBoundary fallbackRender={({ error, resetErrorBoundary }) => (
  <div role="alert"><p>{error.message}</p><button onClick={resetErrorBoundary}>Retry</button></div>
)} onError={reportToMonitoring}>
  <OrdersTable />
</ErrorBoundary>
```

Frameworks already give segment boundaries: `error.tsx` (Next.js), `ErrorBoundary` export (React Router route module). Write a class boundary only when you must ship zero dependencies.

## 8. Resource hints from components (React 19)

```tsx
import { preload, preconnect } from 'react-dom';

export function ProductPage() {
  preconnect('https://cdn.example.com');
  preload('/fonts/inter.woff2', { as: 'font', fetchPriority: 'high' });
  // …
}
```

React de-duplicates and hoists these into `<head>`. https://react.dev/reference/react-dom/preload

## 9. Query hook (TanStack Query v5)

```tsx
// features/orders/api/queries.ts
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { api } from '@/shared/lib/api';
import { orderKeys, type OrderFilters } from './keys';

export function useOrders(filters: OrderFilters) {
  return useQuery({
    queryKey: orderKeys.list(filters),
    queryFn: ({ signal }) => api.orders.list(filters, { signal }), // cancelled on unmount/key change
    staleTime: 30_000,
    placeholderData: keepPreviousData,
  });
}
```

`keepPreviousData` is a `placeholderData` helper in v5 (the v4 `keepPreviousData: true` option is gone); `isPending` replaces `isLoading` for "no data yet". https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5
