/value-ref

Value reference with reactivity

Primary LanguageJavaScript

Deprecation notice

@preact/signals or usignal show best in class performance and are recommended instead.


value-ref test npm version

Value reference with reactivity.

ref = v( init? )

Creates reactive mutable ref object with .value property holding internal value.
Exposes minimal Observable and AsyncIterable interfaces.

ref = v.from(...sources, map?)

Create reactive ref object mapped from passed reactive sources / observables.

import v from './value-ref.js'

let count = v(0)
count.value // 0

const { unsubscribe } = count.subscribe(value => {
  console.log(value)
  return () => console.log('teardown', value)
})
count.value = 1
// > 1
count.value = 2
// > "teardown" 1
// > 2
unsubscribe()

// create mapped ref
let double = v.from(count, value => value * 2)
double.value // 4
count.value = 3
double.value // 6

// create from multiple refs
let sum = v.from(count, double, (count, double) => count + double)

// async iterable
for await (const value of sum) console.log(value)

// dispose refs (automatically unsubscribes on garbage collection)
count = double = sum = null

Note: manual dispose is available as ref[Symbol.dispose], but unnecessary - FinalizationRegistry unsubscribes automatically if reference is lost.

Related

  • templize − template parts with reactive fields support.
  • hyperf − dom fragments builder with reactive fields support.
  • sube − subscribe to any reactive source.
  • subscribable-things − collection of observables for different browser APIs - perfect match with spect.

Similar

observable-value, knockout/observable, mobx/observable, rxjs, vue3/ref, observable, observable proposal, observ, mutant, iron, icaro, introspected, ulive, trkl, emnudge/trkl, usignal, preact/signals, cellx.