tiny-reaction
v1.1.0
Published
Readme
tiny-reaction
A tiny reactive primitive built around a callable getter/setter function.
API
reactive(value)
Creates a reactive cell with an initial value.
import { reactive } from './src/a';
const count = reactive(0);
console.log(count()); // 0
count(1);
console.log(count()); // 1Signature
function reactive<Type>(value: Type): reactive<Type>The returned function acts as both a getter and setter:
count()reads the current value.count(nextValue)writes a new value.
Events
Reactive values support get and set events.
const count = reactive(0);
count.on('set', (next) => {
console.log('count changed to', next);
});
count(2); // logs: count changed to 2Methods
count.on(event, listener)
count.once(event, listener)
count.off(event, listener)on(...): registers a listener for a given event.once(...): registers a listener that is removed after the first trigger.off(...): removes a listener.
get event
The get event runs when the reactive value is read and receives the current value before it's returned.
const name = reactive('alice');
name.on('get', (value) => value.toUpperCase());
console.log(name()); // 'ALICE'set event
The set event runs when a new value is assigned.
const total = reactive(10);
total.on('set', (value) => {
console.log('new total:', value);
});
total(15);Derived values
reactive.effect(fn, deps)
Creates a derived reactive value from other reactive dependencies.
const a = reactive(2);
const b = reactive(3);
const sum = reactive.effect((x, y) => x() + y(), [a, b]);
console.log(sum()); // 5
b(4);
console.log(sum()); // 6reactive.effect.decorator(deps)
A method decorator that turns a method result into a reactive value derived from provided dependencies.
reactive.decorator
A class accessor decorator that initializes a property as a reactive value.
Notes
This package is intentionally minimal and is designed to expose a very small signal-like API around a callable value.
