Derived Values and Effects
In addition to direct mutable variables, DriftJS provides two foundational primitives for managing computed state and side-effects: derive(...) and effect(...).
1. Computed State with Derive
A derived value is a reactive value computed synchronously from other reactive state.
<script>
let firstName = 'Ada';
let lastName = 'Lovelace';
// Automatically recomputed whenever firstName or lastName changes
const fullName = derive(() => `${firstName} ${lastName}`);
let price = 100;
let taxRate = 0.08;
const total = derive(() => price * (1 + taxRate));
</script>
<h1>Welcome, {fullName}!</h1>
<p>Total due: ${total}</p>
Try it live — type in the fields and watch derive(...) recompute automatically:
✦ Both derived values update instantly — no manual wiring required.
How Derive Operates Under the Hood
- At compile time, the AOT compiler inspects the AST inside
derive(() => ...)and extracts all referenced declared variables (e.g.['firstName', 'lastName']). - It registers a
DerivedBindingon theCompiledModule:{ name: "fullName", deps: ["firstName", "lastName"], exprIdx: 4 } - When
firstNameorlastNameis marked dirty, the VM re-evaluates the expression and caches the new value on the scope before any DOM instructions run. - Downstream bytecode instructions referencing
fullNameupdate immediately.
2. Reactive Side Effects with Effect
Use effect(...) to run side effects in response to state changes (such as logging, updating document titles, local storage persistence, or timers).
<script>
let count = 0;
// Runs whenever 'count' changes
effect(() => {
console.log('Count is now:', count);
if (typeof document !== 'undefined') {
document.title = `Count: ${count}`;
}
});
function increment() {
count++;
}
</script>
<button onclick={increment}>Increment: {count}</button>
Effect Cleanup
If an effect sets up a subscription or timer, return a cleanup function from the callback:
<script>
let isRunning = false;
effect(() => {
if (!isRunning) return;
const timer = setInterval(() => {
console.log('Heartbeat tick...');
}, 1000);
// Cleanup function executes before re-running or on unmount
return () => {
clearInterval(timer);
};
});
</script>
3. Lifecycle Hooks: On Mount and On Unmount
For code that must execute strictly when the component enters or leaves the DOM:
<script>
import { onMount, onUnmount } from 'driftjs-dom';
onMount(() => {
console.log('Component mounted in DOM');
});
onUnmount(() => {
console.log('Component destroyed from DOM');
});
</script>