signal()
The signal() function creates reactive state. Read with sig(), write with sig(value).
Syntax
Section titled “Syntax”const sig = signal(initialValue)Parameters
Section titled “Parameters”initialValue
: The initial value of the signal. Can be any type.
Return value
Section titled “Return value”A SignalFunction<T> — a callable function with the following behavior:
sig()— Returns the current value and tracks this read as a dependencysig(newValue)— Sets a new value and notifies all dependentssig.peek()— Returns the current value without tracking
Description
Section titled “Description”Signals are the foundation of Rimitive’s reactivity. When you read a signal inside a computed() or effect(), that read is tracked. When the signal’s value changes, all dependent computeds and effects re-run.
const count = signal(0);
// Readingcount(); // 0 (tracked if inside computed/effect)count.peek(); // 0 (never tracked)
// Writingcount(5); // sets to 5count(count() + 1); // read then writeReactive tracking
Section titled “Reactive tracking”const name = signal('Alice');
// Not reactive — this string is computed once, never updatesconst greeting = `Hello, ${name()}!`;
// Reactive — recomputes when name changesconst greeting = computed(() => `Hello, ${name()}!`);Untracked reads with peek()
Section titled “Untracked reads with peek()”Use peek() when you need the current value without creating a dependency:
effect(() => { // This effect only re-runs when `trigger` changes, // not when `count` changes if (trigger()) { console.log('Count is:', count.peek()); }});Common use cases for peek():
- Event handlers where you need the current value but don’t want reactivity
- Breaking circular dependencies
- Performance optimization when you know a re-run isn’t needed
Examples
Section titled “Examples”Counter
Section titled “Counter”const count = signal(0);const doubled = computed(() => count() * 2);
count(); // 0doubled(); // 0
count(5);count(); // 5doubled(); // 10
count(count() + 1);count(); // 6doubled(); // 12Form state
Section titled “Form state”const form = signal({ name: '', email: '', valid: false,});
// Update one fieldform({ ...form(), name: 'Alice' });
// Derived validationconst isValid = computed(() => { const { name, email } = form(); return name.length > 0 && email.includes('@');});Toggle pattern
Section titled “Toggle pattern”const isOpen = signal(false);
// ToggleisOpen(!isOpen());
// Or create a helperconst toggle = () => isOpen(!isOpen());See also
Section titled “See also”- computed() — Derive values from signals
- effect() — Run side effects when signals change
- Signal Patterns — Common patterns for working with signals