Formula Functions
While you can always use normal functions to compute values based on cells, you can also turn functions into formulas:
- Formulas recompute only when any reactive state used in the formula changes.
- 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";constname =Cell ("John");constlocation =Cell ("New York");constdescription =Formula (() => {return `${name .current } lives in ${location .current }`;});
tsx
import {Cell ,Formula } from "@starbeam/universal";constname =Cell ("John");constlocation =Cell ("New York");constdescription =Formula (() => {return `${name .current } lives in ${location .current }`;});
tsx
import {Cell ,Formula } from "@starbeam/universal";constname =Cell ("John");constlocation =Cell ("New York");constdescription =Formula ((): string => {return `${name .current } lives in ${location .current }`;});
tsx
import {Cell ,Formula } from "@starbeam/universal";constname =Cell ("John");constlocation =Cell ("New York");constdescription =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");