Derived values are cached; inline expressions are not
An expression in JSX runs once per place it appears.
An expression in JSX runs once per place it appears. A derived value runs once per change and is shared:
src/derived-cost.tsxtsx
import { useStore } from "@shadow-js/core";
export const calls = { derived: 0, inline: 0 };
export const controls = { set: (_value: number): void => undefined };
const expensiveDerived = (n: number): number => {
calls.derived += 1;
return n * 2;
};
const expensiveInline = (n: number): number => {
calls.inline += 1;
return n * 2;
};
export function Costs() {
const [count, setCount] = useStore(1);
controls.set = setCount;
const shared = expensiveDerived(count());
return (
<p>
{shared} {shared} {shared} | {expensiveInline(count())} {expensiveInline(count())}{" "}
{expensiveInline(count())}
</p>
);
}
When an expensive computation is read in several places, bind it once (const shared = ..., or
useMemo). A memo also stops propagation: if its result is Object.is-equal to the previous one,
nothing downstream reruns, so derive a small value from a big signal (const isOpen = ids().includes(id))
and let the page read that.