nexa-reactivity
The core reactivity package providing Signals, computed values, effects, batching, and untracked reads.
signal
Creates a reactive value with automatic dependency tracking.
import { signal } from 'nexa-reactivity'
function signal<T>(initial: T): Signal<T>Signal<T>
interface Signal<T> {
get value(): T
set value(val: T)
peek(): T
}| Member | Description |
|---|---|
value | Getter triggers tracking; setter triggers subscribers (uses Object.is() for equality) |
peek() | Read current value without creating a dependency |
Examples:
const count = signal(0)
count.value = 1
console.log(count.value) // 1
console.log(count.peek()) // 1 (no tracking)computed
Derives a value from signals with lazy evaluation and caching.
import { computed } from 'nexa-reactivity'
function computed<T>(fn: () => T): Signal<T>Returns a Signal<T> whose value is lazily recomputed only when dependencies change. Writing to a computed signal's .value is a no-op.
Example:
const a = signal(2)
const b = signal(3)
const sum = computed(() => a.value + b.value)
console.log(sum.value) // 5
a.value = 10
console.log(sum.value) // 13effect
Runs a function whenever its tracked signal dependencies change.
import { effect } from 'nexa-reactivity'
function effect(fn: () => void | (() => void)): EffectReturns an Effect object. Call effect.cleanup() or use the returned effect to stop tracking. If fn returns a function, that cleanup is called before re-execution or disposal.
Examples:
const eff = effect(() => {
console.log(count.value)
})
// With cleanup
effect(() => {
const id = setInterval(() => {}, 1000)
return () => clearInterval(id)
})batch
Groups multiple signal writes, triggering effects only once after all writes complete.
import { batch } from 'nexa-reactivity'
function batch(fn: () => void): voidExample:
const x = signal(1)
const y = signal(2)
effect(() => console.log(x.value + y.value))
// Logs: 3
batch(() => {
x.value = 10
y.value = 20
})
// Logs: 30 (only once)untracked
Reads signals inside fn without creating tracking dependencies.
import { untracked } from 'nexa-reactivity'
function untracked<T>(fn: () => T): TExample:
const a = signal(1)
const b = signal(2)
effect(() => {
console.log(a.value) // tracks a
console.log(untracked(() => b.value)) // does not track b
})