@pfeiferio/ref
v0.1.0
Published
Minimal mutable reference primitive with change notifications
Maintainers
Readme
@pfeiferio/ref
A minimal mutable reference primitive with change notifications.
This package provides a small, explicit Ref abstraction for sharing and observing mutable state.
It is not a reactive framework and intentionally avoids schedulers, dependency tracking, or magic.
Features
- Explicit mutable references
- Change notifications via events
- Deep equality comparison for updates
- Idempotent
ref()creation - No dependencies (Node.js only)
Installation
npm install @pfeiferio/refBasic Usage
import {ref} from '@pfeiferio/ref'
const count = ref(0)
count.on('update', (next, prev) => {
console.log(prev, '→', next)
})
count.value++ref()
Creates a new Ref instance.
If the passed value is already a Ref, the same instance is returned.
const a = ref(1)
const b = ref(a)
a === b // trueThis guarantees reference identity and avoids accidental duplication of state.
unref()
Extracts the value from a Ref, or returns the value unchanged if it is not a Ref.
unref(1) // 1
unref(ref(1)) // 1isRef()
Type guard for checking whether a value is a Ref.
if (isRef(x)) {
console.log(x.value)
}Cloning
If you want an independent copy of a Ref, this must be done explicitly.
const a = ref(1)
const b = cloneRef(a)
b.value = 2
a.value // 1Deep cloning is also available:
const c = cloneRefDeep(a)Semantics
- A
Refrepresents identity, not a container ref()is idempotent- State sharing is always explicit
- Copying state is never implicit
This package is intended as a low-level primitive for controlled state handling.
License
MIT
