Skip to content
On this page

Formula Functions

While you can always use normal functions to compute values based on cells, you can also turn functions into formulas:

  1. Formulas recompute only when any reactive state used in the formula changes.
  2. You can render a formula into the DOM using a Starbeam renderer.

TIP

In practice, it's very uncommon for the overhead of formula functions to outweigh the cost of JavaScript functions, even if they iterate a medium-sized list and do some work for each entry.

To create a formula, pass a function to Formula.

tsx
import { Cell, Formula } from "@starbeam/universal";
 
const name = Cell("John");
const location = Cell("New York");
 
const description = Formula(() => {
return `${name.current} lives in ${location.current}`;
});
tsx
import { Cell, Formula } from "@starbeam/universal";
 
const name = Cell("John");
const location = Cell("New York");
 
const description = Formula(() => {
return `${name.current} lives in ${location.current}`;
});
tsx
import { Cell, Formula } from "@starbeam/universal";
 
const name = Cell("John");
const location = Cell("New York");
 
const description = Formula((): string => {
return `${name.current} lives in ${location.current}`;
});
tsx
import { Cell, Formula } from "@starbeam/universal";
 
const name = Cell("John");
const location = Cell("New York");
 
const description = Formula((): string => {
return `${name.current} lives in ${location.current}`;
});

And you use the formula the same way as a function.

tsx
expect(description()).toBe("John lives in New York");
 
name.set("John Doe");
expect(description()).toBe("John Doe lives in New York");
 
location.set("Los Angeles");
expect(description()).toBe("John Doe lives in Los Angeles");
tsx
expect(description()).toBe("John lives in New York");
 
name.set("John Doe");
expect(description()).toBe("John Doe lives in New York");
 
location.set("Los Angeles");
expect(description()).toBe("John Doe lives in Los Angeles");

Released under the MIT license