Simple reactive state management.
npm install j-atomSimple reactive state management.
``typescript
import {makeAtom, useAtom} from 'j-atom'
import {useAtom} from 'j-atom/react'
// create atom
const atom = makeAtom
const atomWithInitial = makeAtom
// use atom in React component
const value = useAtom(atom)
// getter and setter
atom.value = newValue // set value synchronously
const currentValue = atom.value // get value synchronously
// subscribe for changes
const unsub = atom.sub((newVal, oldVal) => console.log(newVal, oldVal))
const unsub2 = atom.sub(() => console.log(atom.value))
// subscribe with cleanup
const unsub3 = atom.sub((newVal) => {
const handler = () => console.log('cleanup')
window.addEventListener('resize', handler)
return () => window.removeEventListener('resize', handler)
})
// subscribe and run immediately
const unsub4 = atom.sub((newVal, oldVal) => console.log(newVal, oldVal), {now: true})
// subscribe with conditional updates
const unsub5 = atom.sub(
(newVal, oldVal) => console.log(newVal),
{skip(newVal, oldVal) {return newVal === oldVal}} // skip if values are the same
)
unsub() // unsubscribe
`
- makeAtom: Creates an atom with optional initial valueuseAtom(atom: Atom
- : React hook to subscribe to atom changesatom.value
- : Get or set the value synchronouslyatom.sub(subscriber, options?)
- : Subscribe to value changes(newValue, oldValue)
- Returns unsubscribe function
- Subscriber receives and can return cleanup functionnow: boolean
- Options:
- - Call subscriber immediately with current valueskip: (newVal, oldVal) => boolean` - Skip subscriber if returns true
-