# Reacting

> Read when code outside React runs because a value changed. Watch a selection, run an autorun with a cleanup, and write from an autorun without a loop.

## Example

`Realm.watch` runs its effect when the select's result changes, not on the
first run. The chat scrolls to the room's last message when another one
becomes last.

```ts
import { Realm } from "@frondruntime/sorus";
import { $lastInRoom } from "./boxes.ts";
import { app } from "./realm.ts";

// Scrolls to the room's last message when another one becomes last, not on
// the first run.
const stopScroll = Realm.watch(
  app,
  (read) => read($lastInRoom)?.id,
  (id, previous) => {
    if (id !== undefined && previous !== undefined) {
      document.getElementById(id)?.scrollIntoView();
    }
  },
);
```

`Realm.autorun` runs at once, and again when what its last run read changes.
The function it returns is its cleanup, run before the next run and at the
stop: the Escape listener exists only while the composer holds a reply.

```ts
import { Computed, Realm } from "@frondruntime/sorus";
import { app } from "./realm.ts";
import { $composer } from "./state.ts";

// Escape cancels a reply while the composer holds one. The autorun reads
// whether there is a reply, not the composer: typing does not rerun it.
const $replying = Computed.make(app, (read) => read($composer).replyTo !== null, {
  name: "replying",
});

const stopEscape = Realm.autorun(app, (read) => {
  if (!read($replying)) return undefined;
  const onKey = (event: KeyboardEvent) => {
    if (event.key === "Escape") {
      Realm.update(app, (read, write) => write($composer, { ...read($composer), replyTo: null }));
    }
  };
  window.addEventListener("keydown", onKey);
  // Runs before the next run, and when the autorun stops.
  return () => window.removeEventListener("keydown", onKey);
});
```

## Rules

- Reads are tracked in a computed value, a computed function, a watch's
  select, an autorun, and `useSelect`. An update, `Realm.untracked`, a
  watch's effect, and a hook read without tracking and subscribe nothing.
- Derive with a computed value, not an autorun that writes a box: the box is
  a second copy, and the autorun runs on every change whether or not anything reads it.
- Write from an autorun or an effect through `Realm.update`, which runs
  untracked. An autorun that writes what it read reruns until it settles;
  after 100 rounds `sorus/watchers-unsettled` goes to `onError`.
- An error from the first run is thrown to the caller and nothing is
  watched; a later one goes to `onError`. An async effect is a type error,
  because its rejection would reach no one.
- A `scheduler` defers every run after the first until it calls the `run` it
  is handed, so writes between calls join one run. Sorus ships none; the
  host's frame or a timer serves.

## Answers

| Call | Answers |
| --- | --- |
| `Realm.watch(realm, (read) => ..., (value, previous) => ..., { name?, equals?, scheduler?, immediate? })` | The stop function; a second stop does nothing. `equals` decides what counts as a change; `Object.is` by default. `immediate: true` also runs the effect at the call with `previous` `undefined`, ignoring `equals`, and throws `sorus/watch-immediate-in-update` inside an update. |
| `Realm.autorun(realm, (read) => ..., { scheduler? })` | The stop function; a second stop does nothing. |
| `Scheduler` | The type `(run: () => void) => void`. |
| `Realm.isTracking(realm)` | `true` where reads are tracked, `false` elsewhere. |
| `Realm.untracked(realm, (read) => ...)` | What the function returns. Its reads subscribe nothing. |

## With Effect

`Program.watchScoped` is a watch whose effect is an Effect program: the watch
stops when the caller's scope closes, and a change interrupts the effect
still running for the one before it. `Program.changes` is a stream of the
current value, then each change. Both are on
[Programs](../effect/programs.md).

## See also

- [Updates](./updates.md): writing from an effect.
- [Lifecycles](./lifecycles.md): what a watch or an autorun holds observed.
- [Programs](../effect/programs.md): `Program.watchScoped` and `Program.changes` as Effect programs.
- [Hooks](../react/hooks.md): reading in React.
- [Live data](../guides/live-data.md): a watch that refetches when its input changes.
