Skip to content

Cells and bindings ​

A cell is a value a component holds and a binding reads. There are three kinds, and choosing between them is most of what writing a Gesso component is.

Where the value comes fromWhat to useWhat it is
The parentinput(inputs.x, fallback)An input cell the host keeps feeding
This componentinternalState(value)A cell only this component writes
Other cellscomputed(() => ...)A cell that is a function of the cells it reads

The third row is the one people overlook. A value that is a function of other values needs no store and no synchronisation: computed reads the cells its function touches, follows them, and cannot be stale because there is no copy of it anywhere that a change could miss.

Each line keeps its own quantity. The currency comes from the parent and changes both. The total is neither: it is one expression over the two.

tsx
/**
 * One order line, holding all three kinds of value at once.
 *
 *  - `currency` comes from the parent. `input()` reads the prop cell
 *    and gives it a default, so the line follows a parent that changes
 *    its mind, without this body running a second time.
 *  - `quantity` is the line's own. `internalState` is for what
 *    originates here and dies with the component.
 *  - `total` is `computed` from the two above. It reads them as values
 *    and follows them as cells: nothing to keep in sync, nothing to
 *    invalidate, and no way for it to disagree with them.
 */
function OrderLine(inputs: Inputs<{ currency?: Currency }>, _ctx: ComponentContext) {
  const currency = input(inputs.currency, 'USD');
  const quantity = internalState(1);

  const total = computed(
    () => `${currency.value === 'EUR' ? '€' : '$'}${(quantity.value * PRICE_USD * RATES[currency.value]).toFixed(2)}`
  );

  return (
    <row gap={14} y="center">
      <text text="Widget" fontSize={14} color="text" width={70} />
      <Step label="Fewer" glyph="−" onPress={() => (quantity.value = Math.max(1, quantity.value - 1))} />
      <text text={computed(() => String(quantity.value))} fontSize={14} color="text" width={20} textAlign="center" />
      <Step label="More" glyph="+" onPress={() => quantity.value++} />
      <text text={total} fontSize={15} color="text" width={70} textAlign="right" />
    </row>
  );
}

input, a prop that keeps arriving ​

Inputs arrive as cells, not as values, which is what lets the body run once and still follow its parent. inputs.currency is an InputCell, and input(inputs.currency, 'USD') reads it with a default:

ts
function OrderLine(inputs: Inputs<{ currency?: Currency }>) {
  const currency = input(inputs.currency, 'USD');
}

A parent can pass a plain value or an Observable, since every input is Reactive<T> = T | Observable<T>, and the child cannot tell the difference. That is why the example passes currency (a cell) straight down: to OrderLine it is simply an input that changes.

internalState, what the component owns ​

For what originates here and dies with the component: a tooltip's open flag, a caret, a scroll offset, the active tab, the quantity above.

ts
const quantity = internalState(1);
quantity.value++; // marks exactly the bindings that read it

Reading .value is synchronous, writing it is a notification. Nothing is scheduled twice: several writes in one handler mark their nodes and the next frame draws the result once.

The name is on purpose. internalState says where the value came from rather than what it is, so internalState(products) reads as the mistake it usually is. Anything that survives a reload, or that another screen cares about, is application state and belongs on a channel or in a service, not in a component.

computed, a function of other cells ​

ts
const total = computed(() => format(quantity.value * PRICE * RATES[currency.value]));

Write the value as the expression it is, reading each cell with .value. The function runs, computed notes which cells it read, and from then on follows exactly those: when one changes the function runs again, and if the result differs, everything bound to total is written. A cell the function did not read this time is not followed; a branch that reads a different cell next time is.

There is no effect that recomputes total into a second piece of state, and no moment where it disagrees with quantity. Anything that would be a useMemo or a useEffect writing into state is this instead. Read it in a handler with total.value; bind it to a prop like any cell. Pass { equal: 'structural' } when the function builds an object and a rebuilt equal one should not count as a change.

The rule of thumb: if you can write the value as an expression over other cells, it is a computed, not a state. internalState is for a value that nothing else determines.

Observables underneath ​

Every cell is an RxJS Observable, and every prop accepts one, so a value that arrives as a stream rather than a cell binds the same way: text={stream}. A stream is not a cell, though: it has no current value to read with .value, so computed hands its function a read for exactly that case.

ts
const late = computed(read => read(clock) > deadline);

read answers with the stream's latest value and follows it as computed follows a cell, and one subscription is shared by every computed reading the same stream. Pass it a cell and it simply reads it, so a call site does not have to know which it has, and a service that later turns a stream into a cell breaks nothing.

That makes computed the one derivation to reach for, whatever the sources are. derive([a, b], fn) still works and is deprecated: it listed its sources beside the expression, which is a second thing to keep in step with the expression, and a screen with a derive and a computed in it is written in two dialects.

ts
// Before
const scheme = derive([settings.appearance, shell.colorScheme], (chosen, platform) =>
  chosen === 'auto' ? platform : chosen
);

// Now
const scheme = computed(() =>
  settings.appearance.value === 'auto' ? shell.colorScheme.value : settings.appearance.value
);

pipe is still there for everything RxJS is good at, which is streams of events rather than values that are: debouncing, retrying, switching. A binding that is a value has no reason to use it.

One field of a cell ​

select is one field, or one projection, of a cell, as a cell:

ts
const title = select(inputs.track, 'title');
const tags = select(inputs.track, entry => entry.tags.slice(0, 8));

It compares structurally by default, so a projection that rebuilds an equal array or object does not re-bind everything reading it, which is the reason most hand-written comparators exist. Reading four fields of one input is four of these.

An optional input that the parent did not pass is a live cell holding undefined, not a missing one. Binding it straight to a property writes undefined there, which draws as though the property had never been set, so give it a value: input(inputs.tint, INK) for a default, or select for anything else.

What a binding costs ​

A binding is attached to one property of one node. When it emits, that property is written and the node is marked. What that costs depends on which property, and components run once lists the groups: content and paint properties repaint, layout properties run layout again from the nearest ancestor that can absorb the change, and transform does neither, moving the node without touching layout or paint.

Fan-out is free when the nodes share a cell. Ten nodes bound to the same Observable are ten writes from one emission, with no list to re-render and no diff. That is why the two order lines above can share a currency cell without the parent knowing how many lines there are.

What is not free is ten thousand nodes each reading a different slice of one upstream value, which is the next section.

fanOut, when every node wants its own slice ​

A grid, a timeline and a log viewer all arrive at the same shape: one source, and N things on screen each reading one part of it. The natural spelling is a pipe per part:

ts
const cell = cells.pipe(
  map(all => all[key]),
  distinctUntilChanged()
);

It is the one spelling in this guide that does not scale. Every emission runs N pipelines whatever changed, and each pipeline is one more observer on one Subject, which RxJS removes by scanning the list: so unmounting a window of N costs N². At a few dozen nodes none of that is measurable. At ten thousand it is the frame.

fanOut is the same idea with the costs the other way round:

ts
const cells = fanOut(sheet.view.cells, (all, key) => all[key] ?? null, {
  initial: null,
  changed: (next, previous) => next.touched
});

const cell = cells.for(`${row}:${column}`); // a stable cell, made on demand
Text({ text: cell });
cells.release(`${row}:${column}`); // when it leaves the screen

One subscription on the source for the whole registry, whatever N is. Each cell carries its own subject with one observer, so its teardown is the constant-time case. And changed is where the frame is won: a source that knows which keys a patch touched reads only those, so a change to one cell of ten thousand costs one read rather than ten thousand. Leave it out and every live key is read on every emission, which is correct, is what the pipe costs too, and is the honest answer for a source that genuinely does not know.

Measured, ten thousand live keys, against the pipe per key:

mountone key changesunmount
a pipe per key29.8 ms2.2 ms9.7 ms
fanOut10.7 ms2.2 ms4.0 ms
fanOut with changed10.8 ms0.1 ms3.7 ms

A registry is a resource: it holds a key until release and the source until the last key goes. That is deliberate. The surfaces that need it are the ones that mount and unmount deliberately, and a cell that vanished when its last binding did would be rebuilt on every scroll frame by exactly the code that cannot afford it. It is also the one thing here that can be got wrong silently, so a registry that has grown past a couple of thousand keys and released none of them says so once.

It compares by reference, where select and derive compare by content. The opposite default, for the opposite reason: those run once per emission, and this runs once per live key per emission. On ten thousand keys with the source republishing the lot, which is what a scroll does, structural comparison costs 1.9 ms against 0.8. Pass equal: 'structural' when the reader builds a value rather than passing one through. Better still, hand back the same object for an unchanged key, one EMPTY for every cell with nothing in it, and keep the cheap test.

Reach for it when N is large and each emission touches few of them. That second half is the one to check: a source that republishes its whole window on every scroll gets the cheaper mount and teardown and nothing from changed, because every key really did change. A log that appends, a presence list, a dashboard of independent tiles are where the 0.1 ms above comes from.

For a list of components, each is still the answer: a row that is a component already has its own identity and its own inputs, and does not need a registry to give it one.

Cells outside a component ​

internalState is not magic and is not tied to a component: it is a BehaviorSubject with a .value setter. A service can hold one, and a component can bind to it directly. That is how the runtime's own services expose state, and how a small application shares a value between two screens without a channel.

What a cell must not become is the application's data layer. When state outlives a screen, is authoritative, or belongs on another thread, it goes behind a channel. The framework has an opinion about the barrier and none at all about what lives above it.

Values a few screens share ​

A prototype has no application behind it, and still one screen hands the next what was typed: the email on Forgot password, shown by Check email. sharedValue is that, scoped to a node rather than to the app. A node provides a SharedValues, and every component under it asking for the same name has the same cell; with none above, each has a cell of its own at its own start.

tsx
const values = new SharedValues();
<box provide={[provided(SharedValuesKey, values)]}>{steps}</box>;

function ForgotPassword(_inputs: unknown, ctx: ComponentContext) {
  const email = sharedValue(ctx, 'email', '');
  return <TextInput label="Email" {...bind(email)} />;
}

The first component to ask makes the value at its start, reset() puts every value back at its start, and values lists them as they are. A design tool plays a screen this way after the screens before it, and draws the same screen on its board alone, as written.

A screen at a moment ​

A screen as written is where it starts: the list at the top, the tour at its first step. A design shows other moments of it too, a list scrolled far enough for its back-to-top button or a tour at its second step, and a copy of the screen for each would drift from it. StartingInputs draws what it holds with the components in it started from inputs named by component, over what their parents pass:

tsx
<StartingInputs of={{ ScrollArea: { scrollY: 600 }, Tour: { step: 1 } }}>
  <Inbox />
</StartingInputs>

A component reads them as it reads its parent's props, as each one is made, so they start it rather than steer it: a step given without a handler is where the tour starts, and the person moves it on from there, and once the parent passes something new for an input (a dialog's owner closing it), it is the parent's again. A preview of a component's inputs from the inspector goes over them, and ending the preview comes back to them.

A name takes one record for every instance of it, or a list for each in the order they are made, null for one left as written: { Toggle: [null, { on: true }] } turns the second switch on. Nested, the outer one wins for an input both give, so a moment drawn from a moment is the later one.

A component says what it holds now with liveInput(name, read) in its body, and controlled says it for its value, as ScrollArea does for its scrollY. The inspector reports it as an owner's live: what a design tool reads to save a moment of a played screen as one of these.