Skip to content

Cells

The Cell is the most basic kind of reactive value. It's a place to store a single value that is updated atomically.

Atomic Updates

When we say that a Cell is updated atomically, we mean that updates to the value happen in a single operation, even if the value is a list or object.

This differs from the reactive collections, which allow you to update a part of the collection at once.

Creating a Cell

tsx
import { Cell } from "@starbeam/core";
 
const cell = Cell(0);
expect(cell.current).toBe(0);
tsx
import { Cell } from "@starbeam/core";
 
const cell = Cell(0);
expect(cell.current).toBe(0);

Updating a Cell

tsx
cell.set(1);
expect(cell.current).toBe(1);
tsx
cell.set(1);
expect(cell.current).toBe(1);

Updating Based on the Previous Value

As a convenience, you can use the update function to update a cell based on the previous value.

tsx
cell.update((prev) => prev + 1);
expect(cell.current).toBe(2);
tsx
cell.update((prev) => prev + 1);
expect(cell.current).toBe(2);

You don't ever need to use it, because this will work just as well:

tsx
cell.set(cell.current + 1);
expect(cell.current).toBe(3);
tsx
cell.set(cell.current + 1);
expect(cell.current).toBe(3);

You can even use the ++ shorthand to update cell.current:

tsx
cell.current++;
expect(cell.current).toBe(4);
tsx
cell.current++;
expect(cell.current).toBe(4);

INFO

The value of cell.current is always the value that was last set, immediately after it was set. There is no time delay between when the value is set and when your code sees the update under any circumstances.

Description

Whenever you create a reactive value in Starbeam, you can specify a description property. This is a string that is used to describe the value in the developer tools.

tsx
import { Cell } from "@starbeam/core";
 
const person = Cell({ name: "John", age: 30 }, "person");
tsx
import { Cell } from "@starbeam/core";
 
const person = Cell({ name: "John", age: 30 }, "person");

If you specify an equals parameter (see Equality below), you specify the description of the cell as an additional option.

tsx
const person = Cell(
{ name: "John", age: 30 },
{
equals: (a, b) => a.name === b.name && a.age === b.age,
description: "person",
},
);
tsx
const person = Cell(
{ name: "John", age: 30 },
{
equals: (a, b) => a.name === b.name && a.age === b.age,
description: "person",
},
);

Released under the MIT license