hooks

included in @reatom/framework

All atoms and actions have a hooks to they lifecycle, this package expose friendly helpers to use this hooks.

We assume that you already read > Read more in lifecycle guild.

A lot of cool examples you could find in async package docs.

withInit

Operator to set state creator callback to an atom, which is called by first atom subscription (during transaction).

import { atom } from '@reatom/core'
import { withInit } from '@reatom/hooks'

const dateAtom = atom(0).pipe(withInit(() => Date.now()))

onConnect

Subscribe to atom subscription, optionally return cleanup callback (called during effect queue).

Passed ctx have isConnected method which checks the passed atom current status.

import { onConnect } from '@reatom/hooks'

const dispose = onConnect(messagesAtom, (ctx) => {
  const cb = (message) => {
    messagesAtom(ctx, (messages) => [...messages, message])
  }

  WS.on('message', cb)

  return () => WS.off('message', cb)
})

onDisconnect

Shortcut to onConnect return callback.

onUpdate

Derive atom or action update during transaction.

import { onUpdate } from '@reatom/hooks'

const dispose = onUpdate(pagingAtom, (ctx, page) => fetchData(ctx, page))

For computed atoms it is called only when the atom is connected.

spyChange

Spy an atom or an action change in the atom reducer. The difference with onUpdate is that spyChange is a warm link - works inside atom only when it have a connections.

spyChange(CtxSpy, anAtom, (value) => any): isChanged

import { atom } from '@reatom/core'
import { spyChange } from '@reatom/hooks'

export const someAtom = atom((ctx, state = initState) => {
  spyChange(ctx, someAction, (payload) => {
    state = state + payload
  })
  // OR
  if (spyChange(ctx, someAction)) {
    state = state + payload
  }
})