# React 19

You are working in a React 19.3 project with TypeScript. Write code for the version in `package.json`: React 19 removed legacy APIs, made refs and context simpler, and added Actions, `use`, `useEffectEvent`, `<Activity>` and `<ViewTransition>`. Much of what you remember from React 16 to 18 is now the long way round, or gone.

## Before you write code

- Check `react`, `react-dom` and `@types/react` (all 19.x) and the framework (Next.js, React Router, TanStack Start or a Vite app). Server Components and Server Functions exist only where the framework supports them; follow its docs for routing and data.
- Check whether the React Compiler is on: `babel-plugin-react-compiler` in devDependencies, `reactCompiler` in `next.config.*`, or the compiler in the Vite React plugin's options. It changes the memoization rules below.
- When unsure an API exists, read `node_modules/@types/react/index.d.ts` and `node_modules/@types/react-dom/index.d.ts`, not memory.

## Components, refs and context

- Write function components. The only class you may need is an error boundary, and only when the framework (Next.js `error.tsx` or `catchError`) or a library in the project doesn't give you one.
- `ref` is a regular prop. Never wrap a component in `forwardRef`:

```tsx
export function Input({ ref, ...props }: React.ComponentProps<"input">) {
  return <input ref={ref} data-slot="input" {...props} />;
}
```

- A ref callback may return a cleanup function, which React calls on detach instead of calling the ref with `null`. Write ref callbacks with a block body: an arrow that returns an assignment is now a type error.
- `useRef` takes an initial value: `useRef<HTMLDivElement>(null)`. Never read or write `ref.current` during render.
- Render a context as its own provider: `<ThemeContext value={theme}>`. Read it with `use(ThemeContext)`, which, unlike `useContext`, works inside conditions.
- Defaults come from destructuring (`{ size = "md" }`), types from TypeScript: no `defaultProps` or `propTypes` on function components. Use the `React.JSX` namespace, not a global `JSX`.
- Key list items by a stable id, never the index of a list that changes. Change a component's `key` to reset its state.

## Data: use, Suspense and Server Components

- `use(promise)` reads a promise during render: it suspends until the promise resolves and sends a rejection to the nearest error boundary. The promise must come from outside render (a Server Component prop, a cache, a data library). Never `use(fetch(…))` or a promise created in the component: each render makes a new one and suspends again. Don't wrap `use` in `try`/`catch`.
- Give each `<Suspense>` a fallback with the content's layout, placed where content should reveal together.
- Server Components (where supported) are async functions that await data directly, run only on the server and ship no JavaScript: no state, effects or browser APIs. Wrap shared reads in `cache()` so one request reads once. `cacheSignal()` returns a signal that aborts when that render's cache scope ends; pass it to long work.
- `"use client"` marks the module where client code starts, and everything it imports is client code: put it on interactive leaves, not pages. Props crossing it must be serializable: no functions except Server Functions, no class instances.
- `"use server"` marks Server Functions, at the top of a file or of an async function. They are public endpoints: validate input, check the session and authorize inside each one. Modules holding secrets start with `import "server-only"`.

## Actions and forms

An Action is an async function run in a transition: passed to `<form action>` or `<button formAction>`, or called inside `startTransition`. React tracks its pending state, sends thrown errors to the error boundary, and resets the form's uncontrolled fields after a successful form action.

```tsx
"use client";

import { useActionState } from "react";
import { useFormStatus } from "react-dom";

type State = { error?: string; name?: string };

function SubmitButton() {
  const { pending } = useFormStatus();
  return <button type="submit" disabled={pending}>{pending ? "Saving…" : "Save"}</button>;
}

export function NameForm({ save }: { save: (prev: State, data: FormData) => Promise<State> }) {
  const [state, formAction] = useActionState(save, {});
  return (
    <form action={formAction}>
      <input name="name" defaultValue={state.name} aria-invalid={Boolean(state.error)} />
      {state.error && <p role="alert">{state.error}</p>}
      <SubmitButton />
    </form>
  );
}
```

- `useActionState(action, initialState)` returns `[state, dispatch, isPending]`; the action receives `(previousState, payload)`. Return expected errors (and the submitted values, so fields survive the reset) as state; throw only for bugs. Outside a form, call `dispatch` inside `startTransition`.
- `useFormStatus()` comes from `react-dom` and reads the parent `<form>`: call it in a component rendered inside the form, never in the component that renders it.
- `useOptimistic(value, update)` shows the expected result while an Action runs. Call its setter inside the Action; when the Action settles it shows `value` again, so the real result must arrive through props or state.
- State updates after an `await` inside a transition are not part of it: wrap them in `startTransition` again.
- Prefer uncontrolled inputs with `name` and `defaultValue` for forms read as `FormData`; control an input only when its value drives the UI while typing. Reset a form manually with `requestFormReset(form)` from `react-dom`.

## Effects

Effects synchronize with systems outside React: subscriptions, timers, imperative widgets, browser APIs. Before writing one, check that it isn't one of these:

- A value computed from props or state: compute it during render.
- State to reset when a prop changes: render the component with `key={id}`.
- A reaction to a user event: put it in the event handler.
- Data fetching, when the framework has Server Components or loaders, or the project has a data library. When you must fetch in an effect, abort or ignore stale responses in the cleanup.
- Telling a parent about a change: call the parent's callback in the handler that caused it.

Every subscription returns a cleanup; Strict Mode runs an extra setup and cleanup in development to prove it works. List every reactive value as a dependency and never silence the lint rule.

`useEffectEvent` reads the latest props and state from inside an effect without making them dependencies:

```tsx
const onConnected = useEffectEvent(() => showToast(`Connected to ${roomId}`, theme));
useEffect(() => {
  const connection = connect(roomId);
  connection.on("connected", () => onConnected());
  return () => connection.close();
}, [roomId]);
```

Call effect events only from effects; never list them as dependencies or pass them to other components. Subscribe to external stores with `useSyncExternalStore`, not an effect that sets state. `useLayoutEffect` is only for measuring before paint.

## Activity, transitions and View Transitions

- `<Activity mode={visible ? "visible" : "hidden"}>` hides its children while keeping their state and DOM, cleans up their effects while hidden and renders them at low priority. Use it for tabs, panels and back navigation where state should survive, instead of unmounting.
- `startTransition` or `useTransition` for non-urgent updates (switching tabs, filtering a long list); `useDeferredValue(value, initialValue)` keeps typing responsive while a slow child catches up.
- `<ViewTransition>` animates updates made in transitions, deferred values and Suspense reveals, never a plain `setState`; tag them with `addTransitionType`. Give named elements `default="none"` unless they should animate on every transition.

## Metadata and resources

- `<title>`, `<meta>` and `<link>` rendered in any component are hoisted into `<head>`. When the framework has a metadata API (Next.js `metadata`), use that instead.
- A stylesheet rendered as `<link rel="stylesheet" href="…" precedence="default" />` is deduplicated and ordered, and Suspense waits for it to load. `<script async src="…">` is deduplicated too.
- Resource hints come from `react-dom`: `preload(href, { as: "font", type, crossOrigin: "" })`, `preinit(href, { as: "script" | "style" })`, `preconnect` and `prefetchDNS`, called during render or in handlers.

## React Compiler

- When it is on, don't add `useMemo`, `useCallback` or `memo` for performance in new code. Leave existing ones unless you test their removal: it can change effect dependencies.
- It relies on the Rules of React: render is pure (no side effects, no mutating props, state or values after they're used in JSX), hooks run at the top level, and refs are not read during render. Code that breaks them is skipped or behaves wrongly.
- `"use no memo"` at the top of a component or hook opts it out: a temporary escape hatch with a comment saying why. Under `compilationMode: "annotation"`, `"use memo"` opts in.
- Lint with `eslint-plugin-react-hooks`' recommended config, which includes the compiler's rules.

## Do not

- Do not use APIs React 19 removed: `ReactDOM.render`, `hydrate`, `unmountComponentAtNode` and `findDOMNode` (use `createRoot` or `hydrateRoot` from `react-dom/client`, and refs), string refs, legacy context (`contextTypes`, `getChildContext`), `act` from `react-dom/test-utils` (it is in `react`), or `react-test-renderer/shallow`.
- Do not write `forwardRef`, `<Context.Provider>`, `useFormState` (now `useActionState` from `react`) or `element.ref` in new code.
- Do not mirror props into state, chain effects that set state, or fetch in `useEffect` where the framework or a data library can.
- Do not read `Date.now()` or `Math.random()`, or format with the runtime's locale, during render in server-rendered components: they cause hydration mismatches.

## Before you finish

- Run the type checker and the linter with the React hooks rules on, and fix what they report.
- Run in development with Strict Mode: no warnings, no double requests, no leaked subscriptions.
- Submit every form you touched: pending state, returned errors, reset fields, and, with Server Functions, a submit before hydration.
- Check the console for hydration mismatch warnings on server-rendered pages.
