# @zwire/react

> React 18/19 Compiler-safe hooks, concurrent-abort-safe SelectorStabilizer, and mirror /tx, /collections, /resource, /protocol subpaths.

React 18 / 19 Compiler-safe hooks for [`@zwire/core`](https://www.npmjs.com/package/@zwire/core): tearing-free reads, optimistic mutations, incremental lists, async resources and SSR hydration.

## Install

```bash
npm install @zwire/core @zwire/react
```

| Entry | Mirrors | Exports |
| :--- | :--- | :--- |
| `@zwire/react` | `@zwire/core` | `ScopeProvider`, `useScope`, `useScoped`, `useSignal`, `useAtom`, `useSelector`, `useDeferredSignal` |
| `@zwire/react/tx` | `@zwire/core/tx` | `useOptimisticLayer`, `useOptimisticAction`, `useDraft` |
| `@zwire/react/collections` | `@zwire/core/collections` | `useCollectionTopK`, `useCollectionRange`, `useCollectionItem`, `useCollectionSize` |
| `@zwire/react/resource` | `@zwire/core/resource` | `useResource`, `useSuspenseResource` |
| `@zwire/react/protocol` | `@zwire/core/protocol` | `useHydrate`, `HydrationBoundary` |

Every hook takes an optional options object as its last argument; `{ scope }` overrides the scope from `ScopeProvider`.

## Quick start

```tsx
import { atom } from '@zwire/core';
import { useAtom, useSelector, useSignal } from '@zwire/react';

const count = atom(0);

function Counter() {
  const value = useSignal(count);
  const parity = useSelector(count, (n) => n % 2);
  const [, setCount] = useAtom(count);
  return <button onClick={() => setCount((n) => n + 1)}>{value} ({parity})</button>;
}
```

## Recipes

### State per scope

```ts
// state/account.ts: a definition at module level, instantiated once per scope
import { scoped } from '@zwire/core';
import { createQueryCollection } from '@zwire/core/collections';
import { hydratable } from '@zwire/core/protocol';
import { resource } from '@zwire/core/resource';

export const account = scoped((scope) => ({
  balance: hydratable('balance', 0, { scope }),
  orders: createQueryCollection<Order, number>({
    scope,
    getId: (order) => order.id,
    compare: (a, b) => b.qty - a.qty,
  }),
  profile: resource((signal) => api.profile({ signal }), { scope, lazy: true }),
}));
```

```tsx
import { ScopeProvider, useScoped, useSignal } from '@zwire/react';

function Balance() {
  const { balance } = useScoped(account); // the instance for the nearest ScopeProvider
  return <output>{useSignal(balance)}</output>;
}

export function App() {
  // Without a `scope` prop the provider creates a scope and disposes it on unmount.
  return (
    <ScopeProvider>
      <Balance />
    </ScopeProvider>
  );
}
```

Atoms belong to the scope they were created in. `scoped()` keeps the definition at module level and builds one instance per scope on first use, so a `ScopeProvider` (or a server request) gets its own state. Outside components, call the definition directly: `account(scope).balance.set(1000)`.

### Optimistic mutation

```tsx
import { useOptimisticAction, useOptimisticLayer } from '@zwire/react/tx';

function Reserve() {
  const { balance } = useScoped(account);

  // One layer per call: reverted if the request fails, settled with the server's answer.
  const reserve = useOptimisticAction(
    async (tx, amount: number) => {
      tx.update(balance, (b) => b - amount);
      return api.reserve(amount, { signal: tx.signal });
    },
    { settle: (result) => balance.set(result.balance) },
  );

  return (
    <>
      <button disabled={reserve.pending} onClick={() => reserve.run(150)}>
        Reserve 150
      </button>
      {reserve.error ? <p role="alert">Could not reserve</p> : null}
    </>
  );
}
```

- `run(...args)` never throws; a failure lands in `error`. `runAsync(...args)` returns the promise.
- Calls made while one is in flight run as parallel layers that rebase in order. Pass `concurrency: 'latest'` to abort the earlier call or `'drop'` to ignore the new one.
- A call keeps running if the component unmounts, so the server's answer still lands. Pass `abortOnUnmount: true` to abort instead.

For a layer the UI holds open itself, use the manual handle:

```tsx
const hold = useOptimisticLayer();
<button onClick={() => (hold.active ? hold.revert() : hold.update(balance, (b) => b - 150))}>
  {hold.active ? 'Release' : 'Hold 150'}
</button>;
```

The first `update` opens the layer, `settle(serverUpdate?)` or `revert()` closes it, and unmounting reverts it. `useDraft()` gives the same kind of handle for an STM draft (`draft.set`, `draft.get`, `draft.commit`, `draft.discard`).

### Lists

```tsx
import {
  useCollectionItem,
  useCollectionRange,
  useCollectionSize,
} from '@zwire/react/collections';

function Orders({ page }: { page: number }) {
  const { orders } = useScoped(account);
  const rows = useCollectionRange(orders, page * 20, 20);
  const total = useCollectionSize(orders);
  return (
    <>
      <p>{total} orders</p>
      {rows.map((order) => (
        <OrderRow key={order.id} id={order.id} />
      ))}
    </>
  );
}

function OrderRow({ id }: { id: number }) {
  const { orders } = useScoped(account);
  const order = useCollectionItem(orders, id); // re-renders only when this row changes
  return <li>{order?.qty}</li>;
}
```

A `filter` option must be referentially stable (module-level, `useCallback`, or React Compiler): a new function builds a new view.

### Async resources

```tsx
import { useResource, useSuspenseResource } from '@zwire/react/resource';

function Profile() {
  const profile = useResource(useScoped(account).profile);
  if (profile.status === 'pending') return <Spinner />;
  if (profile.status === 'error') return <button onClick={profile.refetch}>Retry</button>;
  if (profile.status === 'disposed') return null;
  return <p style={{ opacity: profile.pending ? 0.5 : 1 }}>{profile.data.name}</p>;
}

// With <Suspense> and an error boundary around it:
function ProfileName() {
  return <p>{useSuspenseResource(useScoped(account).profile).name}</p>;
}
```

`data` keeps the last successful value while refreshing and after an error. Create resources in a `scoped()` definition or at module level, not inside a component that may suspend, where each retry would create a new one.

### Scope and SSR

Hydrate the scope before any component reads it. With the Next.js App Router, pass server data to a client component:

```tsx
'use client';
import { ScopeProvider } from '@zwire/react';
import { HydrationBoundary } from '@zwire/react/protocol';
import type { HydratedState } from '@zwire/core/protocol';

export function Providers({ state, children }: { state: HydratedState; children: React.ReactNode }) {
  return (
    <ScopeProvider mode={typeof window === 'undefined' ? 'ssr' : 'client'}>
      <HydrationBoundary state={state}>{children}</HydrationBoundary>
    </ScopeProvider>
  );
}
```

`state` maps the keys of `hydratable(key, ...)` atoms to values (`{ balance: 1000 }`). The same object is applied to a scope at most once; a new object passed later is applied after commit. `mode` is explicit because React Native and DOM-less test renderers look like a server to environment checks.

When the server serializes state itself, create the scope there, render inside `<ScopeProvider scope={scope}>`, call `dehydrate(scope)` from `@zwire/core/protocol`, and dispose the scope.

## Notes

- **Selectors on stores.** `useSelector(store, selector)` on an `ObjectStore` or `DeepStore` subscribes to the fields the selector reads, so a new selector function resubscribes. Prefer `useSignal(store.field('name'))`, or define the selector at module level.
- **`useDeferredSignal(signal)`** returns `{ value, isPending }` backed by `useDeferredValue`.

## Migrating from 0.3

| 0.3 | 0.4 |
| :--- | :--- |
| `useStoreScope()` | `useScope()` |
| `useAtomValue(signal)` | `useSignal(signal)` |
| `useSignal(signal, scope)` | `useSignal(signal, { scope })` |
| `useAtom(signal, scope)` | `useAtom(signal, { scope })` |
| `useSelector(src, sel, eq, scope)` | `useSelector(src, sel, { equals: eq, scope })` (`useSelector(src, sel, eq)` is unchanged) |
| `useOptimistic(createOptimisticLayer)` from `@zwire/react/hooks`, then `layer().update(...)` | `useOptimisticLayer()` from `@zwire/react/tx`, then `layer.update(...)` |
| `useDraft(createDraft)` from `@zwire/react/hooks`, then `draft().set(...)` | `useDraft()` from `@zwire/react/tx`, then `draft.set(...)` |
| `useCollectionTopK(col, k, scope)` from `@zwire/react/hooks` | `useCollectionTopK(col, k, { scope })` from `@zwire/react/collections` |
| `useDeferredAtomValue(signal)` | `useDeferredSignal(signal)` |

See the [API reference](https://github.com/kjmin-dev/zwire/blob/main/docs/API.md#71-zwirereact) for full signatures and the [order book example](https://github.com/kjmin-dev/zwire/tree/main/examples/wasm-orderbook).
