Reactive state — demo
Counter with state, computedState, effect, and onDestroy working together. Demonstrates the four pieces every reactive logic class uses.
What it shows
- A
countsignal updated by +, −, and Reset buttons. - A
doubledcomputedStatederived fromcount— memoised, no manual subscription. - An
effectthat persistscounttolocalStorageon every change. Reload the page; the value survives. - A side clock driven by
setInterval, cleaned up viaonDestroyon unmount.
The logic
import {
computedState,
effect,
onDestroy,
state,
} from '@react-logic/react-logic';
class CounterLogic {
count = state(Number(localStorage.getItem('count') ?? 0));
doubled = computedState(() => this.count() * 2);
now = state(Date.now());
constructor() {
effect(() => localStorage.setItem('count', String(this.count())));
const id = setInterval(() => this.now(Date.now()), 1000);
onDestroy(() => clearInterval(id));
}
inc() { this.count(this.count() + 1); }
dec() { this.count(this.count() - 1); }
reset() { this.count(0); }
}
The React component does nothing but read signals and wire button clicks. useLogic handles the subscription.
Run it
nx serve demo-reactive-state