# Atoms

> For the complete documentation index, see [llms.txt](https://ensforge.com/llms.txt).

Look up the atom layer of @ensforge/react/atoms that the hooks are built on, for reading ENS data outside of React components.

Source: https://ensforge.com/docs/reference/react/atoms

Exports of `@ensforge/react/atoms`. See [Atoms](/docs/react/atoms).

## Exports [#exports]

### `ensAtom` [#ensatom]

**Unstable**

The atom of one read: cached per client (chain, account and indexer), action and options,
refreshed when a write touches a name or address in its options, and serializable for server
rendering. Each freshness gets its own atom over the shared read.

```ts
function ensAtom<action extends Action>(client: Ensforge.Client, action: action, options: ActionOptions<action>, freshness: Freshness = {}): ReadAtom<ActionValue<action>, ActionError<action>>
```

Use to compose ENS reads into your own atoms, or to read them outside React hooks. Hooks such
as `useRead` use the same atoms.

```ts title="Composing reads"
import { Actions } from "@ensforge/sdk"
import { ensAtom } from "@ensforge/react/atoms"
import { Atom } from "effect/reactivity"

const profile = Atom.make((get) => ({
  address: get(ensAtom(ens, Actions.record.getAddress, { name: "nick.eth" })),
  avatar: get(ensAtom(ens, Actions.record.getAvatar, { name: "nick.eth" })),
}))
```

### `ensPagesAtom` [#enspagesatom]

**Unstable**

The paginated atom of an indexer list, such as `indexer.getSubnames`. Pages accumulate as
they load; a write touching the list's name or account starts it over.

```ts
function ensPagesAtom<action extends PageAction>(client: Ensforge.Client, action: action, options: Omit<ActionOptions<action>, "cursor">): PagesAtom<ActionValue<action>, ActionError<action>>
```

```ts title="Loading subnames page by page"
import { Actions } from "@ensforge/sdk"
import { ensPagesAtom } from "@ensforge/react/atoms"

const subnames = ensPagesAtom(ens, Actions.indexer.getSubnames, { name: "ens.eth" })
registry.set(subnames, undefined) // load the next page
```

### `ensWriteAtom` [#enswriteatom]

**Unstable**

Atoms for one write action. Each call makes new atoms, so every form or button has its own
state; hooks keep one per component.

```ts
function ensWriteAtom<action extends Action>(client: Ensforge.Client, action: action): WriteAtom<ActionOptions<action>, ActionValue<action>, ActionError<action>>
```

- `run` and `steps` show the latest write started; mount `run` while writing through it.
- Writes never interrupt each other, and resetting interrupts none: a sent transaction cannot
  be taken back. Each `send` still ends with its own write's result.
- Plan events (`waiting`, `submitted`, `confirmed`, `failed`) collect in `steps`.
- After a write, reads of the names and accounts it touched refresh: chain reads once its
  transactions are mined, indexer reads once the indexer has caught up. A write that fails
  after a step was confirmed refreshes them too. Signatures (`primaryName.signClaim`) send no
  transaction and refresh nothing.

```ts title="Sending a write from an atom"
import { Actions } from "@ensforge/sdk"
import { ensWriteAtom } from "@ensforge/react/atoms"

const setRecords = ensWriteAtom(ens, Actions.record.set)
registry.mount(setRecords.run)
registry.set(setRecords.run, { name: "alice.eth", texts: { url: "https://alice.xyz" } })
```

### `invalidate` [#invalidate]

**Unstable**

Refetches every cached read of the given names and accounts, chain and indexer reads alike.

```ts
function invalidate(registry: AtomRegistry.AtomRegistry, client: Ensforge.Client, subjects: { readonly names?: readonly string[]; readonly addresses?: readonly string[] }): void
```

Use after changes ensforge did not make, such as a transaction sent by another app. Writes
made through ensforge refresh their reads on their own.

```ts title="Refreshing a name after an external change"
import { invalidate } from "@ensforge/react/atoms"

invalidate(registry, ens, { names: ["alice.eth"] })
```

### `optionsKey` [#optionskey]

**Unstable**

A stable string for an action's options: keys sorted, `undefined`, callbacks and `signal`
dropped, the top-level `name`, `names` and `parent` normalized, top-level addresses lowercased
and bigints written as `123n`. Nested fields are data (a text record called `name`), kept as
given.

```ts
function optionsKey(options: unknown): string
```

### `readKey` [#readkey]

**Unstable**

The key a read is cached, hydrated and invalidated under:
`ensforge:<chainId>:<account>:<indexer>:<path>:<options>`, with the client's account
(lowercase) and indexer key (`Indexer.key`) empty when it has none. It names the client by what changes a
read's answer, not by object, so it is the same on the server and in the browser.

```ts
function readKey(client: Ensforge.Client, action: Action, options: unknown): string
```

### `Action` [#action]

Any ensforge action from `@ensforge/sdk` or `@ensforge/sdk/effect`, or one of a write's
`.prepare`, `.simulate` and `.estimateGas`: a function of a client and options, named by its
`path`.

```ts
type Action = ((client: Ensforge.Client, options: never) => unknown) & { readonly path: string; };
```

| Field | Type | Description |
| --- | --- | --- |
| `path` | `string` |  |

### `ActionError` [#actionerror]

Error an action fails with: the Effect action's error channel, or any ensforge error for
Promise actions.

```ts
type ActionError<action extends Action> = ReturnType<action> extends Effect.Effect<unknown, infer error, unknown> ? error : Errors.AnyError;
```

### `ActionOptions` [#actionoptions]

Options an action takes.

```ts
type ActionOptions<action extends Action> = Parameters<action>[1];
```

### `ActionValue` [#actionvalue]

Value an action resolves with.

```ts
type ActionValue<action extends Action> = ReturnType<action> extends Promise<infer value> ? value : ReturnType<action> extends Effect.Effect<infer value, unknown, unknown> ? value : never;
```

### `Freshness` [#freshness]

How long a read stays fresh and cached. Each hook's settings apply to it alone; hooks with
other settings still share the read's value and requests.

```ts
type Freshness
```

| Field | Type | Description |
| --- | --- | --- |
| `staleTime` (optional) | `Duration.Input` | After this long, the next mount or window focus refetches in the background while the cached value is shown (stale-while-revalidate). `Duration.infinity` never does. Without it, a value hydrated from the server is stale after 30 seconds; a failed read is always stale, so a remount retries it. |
| `idleTTL` (optional) | `Duration.Input \| "forever"` | How long an unused read stays cached; `"forever"` or `Duration.infinity` keeps it. With hooks of several settings, the longest applies. |
| `refetchInterval` (optional) | `Duration.Input` | Refetch on this interval while the read is in use, in the browser only. |
| `refreshOnWindowFocus` (optional) | `boolean` | Refetch when the window regains focus (respecting `staleTime` when set). |

### `PageAction` [#pageaction]

An indexer action that returns pages and takes a `cursor`, such as `indexer.getSubnames`.

```ts
type PageAction = Action & (( client: never, options: never, ) => | Promise<{ readonly items: readonly unknown[]; readonly cursor: string | null }> | Effect.Effect< { readonly items: readonly unknown[]; readonly cursor: string | null }, unknown >);
```

| Field | Type | Description |
| --- | --- | --- |
| `path` | `string` |  |

### `PagesAtom` [#pagesatom]

**Unstable**

Pages of an indexer list as an atom: its value holds every page loaded so far, and writing to
it loads the next one.

```ts
type PagesAtom<page, error> = Atom.Writable<Atom.PullResult<page, error>, void>;
```

### `ReadAtom` [#readatom]

**Unstable**

A read atom: an Effect Atom holding the read's `AsyncResult`.

```ts
type ReadAtom<value, error> = Atom.Atom<AsyncResult.AsyncResult<value, error>>;
```

### `WriteAtom` [#writeatom]

**Unstable**

A write as atoms: `run` holds the latest write's result and sends one when set; `steps` holds
that write's plan events; `send` sends one and ends with its own result.

```ts
type WriteAtom<options, value, error>
```

| Field | Type | Description |
| --- | --- | --- |
| `run` | `Atom.Writable<AsyncResult.AsyncResult<value, error>, options \| Atom.Reset>` | The latest write's result. Setting options sends a write; `Atom.Reset` clears the result. |
| `steps` | `Atom.Writable<readonly Plan.Event[]>` |  |
| `send` | `(options: options) => Effect.Effect<value, error, AtomRegistry.AtomRegistry>` | Sends a write and ends with its own result, even when later writes start while it runs. `run` and `steps` show it until a later one starts. |