Computed
A computed (or "computed value"), it's a derived signal, which means that its value depends on the value of a given signal, a computed value is readonly, you can only react from it changes, let's have a look:
Creating a derived signal
Component('app-counter', () => {
const counter = signal(1);
const doubleCounter = computed(() => counter() * 2)
return () => html`<button>Double of ${counter()} is ${doubleCounter()}</button>`
})That's it, as result we are going to have:
<app-counter>
<button>Double of 1 is 2</button>
</app-counter>You can even have more than a single computed signal dependency at a time, like this:
Component('app-username', () => {
const firstname = signal('John');
const surname = signal('Doe');
const fullname = computed(() => `${firstname()} ${surname()}`)
return () => html`<button>${fullname()}</button>`
})Then, DOM result will be:
Reacting to computed value changes
As computed value is a derived signal, if any of its dependency changes, the computed , when gets called, will get a new value based on its signal dependencies current value, this way:
When the button gets clicked, firstname signal will be updated, as fullname depends on it, the result displayed in the DOM will be:
Last updated