Concept Explanation
Think of a spreadsheet. When you type =A1 + B1 into cell C1, then change A1, cell C1 updates automatically. You never wrote code saying "when A1 changes, recompute C1" — the spreadsheet tracks the dependency for you.
Signals bring that magic to JavaScript. A signal is a value that knows who depends on it. When the value changes, only the exact pieces of UI that used it re-run — not the whole component. That's why frameworks like Solid, Angular, and Preact adopted them: they're faster than re-rendering everything.
Syntax or Core Structure
// A tiny signal in action
const count = signal(0);
// An "effect" auto-subscribes to any signal it reads
effect(() => {
console.log("Count is now:", count.value);
});
count.value = 5; // the effect re-runs automatically → "Count is now: 5"
The key idea: reading count.value inside an effect registers that effect as a listener. Writing count.value notifies every listener.
Signals vs. Traditional State
- Traditional state: change state → re-render the whole component → diff the DOM.
- Signals: change a signal → update only the one text node that used it. No diffing.
Common Mistakes
- Reading Outside an Effect: Accessing
count.valueoutside a tracked context won't subscribe you to changes. - Forgetting Derived Values: Use a
computedsignal for values built from others, so they cache and only recompute when a dependency changes.
Best Practices
- Keep Signals Small: One signal per independent piece of state, so updates stay surgical.
- Clean Up Effects: Long-lived effects should be disposed when their owner is destroyed, to avoid leaks.
Practice Exercises
- The Counter: Build
signalandeffectfunctions so changing a value auto-logs it. - The Computed: Add a
computedthat derivesdouble = count * 2and updates on its own. - The DOM Binder: Wire a signal to a
<span>so its text updates whenever the signal changes.