Signal Creation and Reading
You'll learn how to create a signal and access its current value using the basic getter/setter pattern found in signal implementations.
What Is Signal Creation?
In reactive programming, a signal is a container that holds a value and notifies dependents when that value changes. Creating a signal typically involves calling a factory function that returns both a way to read the current value and a way to write (update) it.
The most common pattern uses a getter/setter pair: the getter retrieves the current value, while the setter updates it. Some implementations return a function that acts as both getter (when called with no arguments) and setter (when called with a value).
The Basic Pattern
Think of a signal like a wrapper around a variable with superpowers—it doesn't just store a value, it remembers who's watching and can notify them when things change.
// Basic signal creation (simplified implementation)
function createSignal(initialValue) {
let value = initialValue;
// Getter: read current value
const read = () => value;
// Setter: update value
const write = (newValue) => {
value = newValue;
// (Future: notify dependents)
};
return [read, write];
}
// Usage
const [count, setCount] = createSignal(0);
console.log(count()); // 0
setCount(5);
console.log(count()); // 5
The getter is a function call (not direct property access), which allows the signal system to track who's reading the value—critical for automatic reactivity.
Key Takeaway: Signals use a getter/setter pattern where reading the value is an explicit function call, enabling the reactive system to track dependencies and trigger updates when the underlying value changes.