signal
Holds a value and notifies subscribers when it changes.
interface Signal<T> { // Get or set the value (value?: T): T; // Set the value set: (value: T) => void; // Subscribe to changes subscribe: (fn: () => void) => () => void // Unsubscribe from changes unsubscribe: (fn: () => void) => void // Cleanup all subscribers cleanup: () => void;}
/** * @param initialValue The initial value for the signal * @returns A signal function with methods */signal<T>(initialValue: T): Signal<T>
Get a signal by calling it with no arguments.
import { signal } from '@hellajs/core';
// Create a signal with an initial valueconst count = signal(5);
// Read the current valueconsole.log(count()); // 5
Update a signal value using the set method, or by calling it with a new value.
// Update using set methodcount.set(10);console.log(count()); // 10
// Update using function callcount(20);console.log(count()); // 10
Subscribe
Section titled “Subscribe”Subscribe to signals (or use effect) to get notified when the value changes.
// Subscribe to changesconst unsubscribe = count.subscribe(() => { console.log('Count changed:', count());});
// Stop listening for changesunsubscribe();
or similar to an eventListener:
const subscribeFn = () => { console.log('Count changed:', count());}
// Subscribe to changescount.subscribe(subscribeFn);
// Stop listening for changescount.unsubscribe(subscribeFn);
Cleanup
Section titled “Cleanup”Call cleanup when the signal is no longer needed. It will remove all subscribers and stop notifying them. Cleanup is required for global signals only. Signals created inside a component function are automatically cleaned when the component is unmounted.
count.cleanup();