Effect
An effect is a mechanism designed to dispatch side effects (such as interface updates, API calls, or modifications to external data) whenever changes in its dependencies, like signals or computed values, are detected, let's have a look:
Dispatching a side effect
That's simple, just wrap a signal reading inside effect's callback function.
Component('app-component', () => {
const counter = signal(0);
effect(() => {
console.log('counter new value is', counter());
});
const increment = () => {
signal.set(counter() + 1);
}
return () => html`<button onclick="${increment}">Increment<button>`;
})In the code snippet above, every time counter value changes, effect callback function will execute, writing the message in the browser console.
Handling async side effects
Effect also can handle async operations, this way:
Important: a signal cannot be written from within an effect if it is a dependency on that effect!
See an example:
This approach in VistaJS avoids infinite update cycles, however, you can still update signals within an effect as long as it is not its dependency, just like in the following example:
You are going to see the result in the DOM:
Last updated