Skip to content

jotaijs/jotai-effect

Repository files navigation

Effect

jotai-effect is a utility package for reactive side effects in Jotai.

Install

npm install jotai-effect

observe

observe mounts an effect to watch state changes on a Jotai store. It's useful for running global side effects or logic at the store level.

If you don't have access to the store object and are not using the default store, use atomEffect or withAtomEffect instead.

Signature

type Cleanup = () => void

type Effect = (
  get: Getter & { peek: Getter }
  set: Setter & { recurse: Setter }
) => Cleanup | void

type Unobserve = () => void

function observe(effect: Effect, store?: Store): Unobserve

effect: A function for observing and reacting to atom state changes.

store: A Jotai store to mount the effect on. Defaults to the global store if not provided.

returns: A stable function that removes the effect from the store and cleans up any internal references.

Usage

import { observe } from 'jotai-effect'

// activate the effect on the default store
const unobserve = observe((get, set) => {
  set(logAtom, `someAtom changed: ${get(someAtom)}`)
})

// Clean up the effect
unobserve()

This allows you to run Jotai state-dependent logic outside React's lifecycle, ideal for application-wide effects.

Usage With React

When using a Jotai Provider, pass the store to both observe and the Provider to ensure the effect is mounted on the correct store.

const store = createStore()
const unobserve = observe((get, set) => {
  set(logAtom, `someAtom changed: ${get(someAtom)}`)
}, store)

<Provider store={store}>...</Provider>

Using observe in a useEffect

function effect(get: Getter, set: Setter) {
  set(logAtom, `someAtom changed: ${get(someAtom)}`)
}

function Component() {
  const store = useStore()
  useEffect(() => observe(effect, store), [store])
}

atomEffect

atomEffect creates an atom for declaring side effects that react to state changes when mounted.

Signature

function atomEffect(effect: Effect): Atom<void>

effect: A function for observing and reacting to atom state changes.

Usage

import { atomEffect } from 'jotai-effect'

const logEffect = atomEffect((get, set) => {
  set(logAtom, get(someAtom)) // Runs on mount or when someAtom changes

  return () => {
    set(logAtom, 'unmounting') // Cleanup on unmount
  }
})

// activates the atomEffect while Component is mounted
function Component() {
  useAtom(logEffect)
}

withAtomEffect

withAtomEffect binds an effect to a clone of the target atom. The effect is active while the cloned atom is mounted.

Signature

function withAtomEffect<T>(targetAtom: Atom<T>, effect: Effect): Atom<T>

targetAtom: The atom to which the effect is bound.

effect: A function for observing and reacting to atom state changes.

Returns: An atom that is equivalent to the target atom but having a bound effect.

Usage

import { withAtomEffect } from 'jotai-effect'

const valuesAtom = withAtomEffect(atom(null), (get, set) => {
  set(valuesAtom, get(countAtom))
  return unsubscribe
})

Effect Behavior

  • Cleanup Function: The cleanup function is invoked on unmount or before re-evaluation.

    Example
    atomEffect((get, set) => {
      const intervalId = setInterval(() => set(clockAtom, Date.now()))
      return () => clearInterval(intervalId)
    })
  • Resistant to Infinite Loops: atomEffect avoids rerunning when it updates a value that it is watching.

    Example
    const countAtom = atom(0)
    atomEffect((get, set) => {
      get(countAtom)
      set(countAtom, increment) // Will not loop
    })
  • Supports Recursion: Recursion is supported with set.recurse but not in cleanup.

    Example
    const countAtom = atom(0)
    atomEffect((get, set) => {
      const count = get(countAtom)
      const timeoutId = setTimeout(() => {
        set.recurse(countAtom, increment)
      }, 1000)
      return () => clearTimeout(timeoutId)
    })
  • Supports Peek: Use get.peek to read atom data without subscribing.

    Example
    const countAtom = atom(0)
    atomEffect((get, set) => {
      const count = get.peek(countAtom) // Will not add countAtom as a dependency
    })
  • Executes In The Next Microtask: effect runs in the next available microtask after synchronous evaluations complete.

    Example
    const countAtom = atom(0)
    const logAtom = atom('')
    const logCounts = atomEffect((get, set) => {
      set(logAtom, `count is now ${get(countAtom)}`)
    })
    const setCountAndReadLog = atom(null, async (get, set) => {
      get(logAtom) // 'count is now 0'
      set(countAtom, increment) // effect runs in next microtask
      get(logAtom) // 'count is now 0'
      await Promise.resolve()
      get(logAtom) // 'count is now 1'
    })
    store.sub(logCounts, () => {})
    store.set(setCountAndReadLog)
  • Batched Updates: Multiple synchronous updates are batched as a single atomic transaction.

    Example
    const tensAtom = atom(0)
    const onesAtom = atom(0)
    const updateTensAndOnes = atom(null, (get, set) => {
      set(tensAtom, (value) => value + 1)
      set(onesAtom, (value) => value + 1)
    })
    const combos = atom([])
    const effectAtom = atomEffect((get, set) => {
      const value = get(tensAtom) * 10 + get(onesAtom)
      set(combos, (arr) => [...arr, value])
    })
    store.sub(effectAtom, () => {})
    store.set(updateTensAndOnes)
    store.get(combos) // [00, 11]
  • Conditionally Running Effects: atomEffect only runs when mounted.

    Example
    atom((get) => {
      if (get(isEnabledAtom)) {
        get(effectAtom)
      }
    })
  • Idempotency: atomEffect runs once per state change, regardless of how many times it is referenced.

    Example
    let i = 0
    const effectAtom = atomEffect(() => {
      get(countAtom)
      i++
    })
    store.sub(effectAtom, () => {})
    store.sub(effectAtom, () => {})
    store.set(countAtom, increment)
    await Promise.resolve()
    console.log(i) // 1

Dependency Management

Aside from mount events, the effect runs when any of its dependencies change value.

  • Sync: All atoms accessed with get during the synchronous evaluation of the effect are added to the atom's internal dependency map.

    Example
    atomEffect((get, set) => {
      // updates whenever `anAtom` changes value but not when `anotherAtom` changes value
      get(anAtom)
      setTimeout(() => {
        get(anotherAtom)
      }, 5000)
    })
  • Async: Use an abort controller to cancel pending fetch requests and promises.

    Example
    class AbortError extends Error {}
    
    atomEffect((get, set) => {
      const abortController = new AbortController()
      fetchData(abortController.signal).catch((error) => {
        if (error instanceof AbortError) {
          // async cleanup logic here
        } else {
          throw error
        }
      })
      return () => abortController.abort(new AbortError())
    })
  • Cleanup: get calls in cleanup do not add dependencies.

    Example
    atomEffect((get, set) => {
      set(logAtom, get(valueAtom))
      return () => {
        get(idAtom) // Not a dependency
      }
    })
  • Dependency Map Recalculation: Dependencies are recalculated on every run.

    Example
    const isEnabledAtom = atom(true)
    
    atomEffect((get, set) => {
      // if `isEnabledAtom` is true, runs when `isEnabledAtom` or `anAtom` changes value
      // otherwise runs when `isEnabledAtom` or `anotherAtom` changes value
      if (get(isEnabledAtom)) {
        const aValue = get(anAtom)
      } else {
        const anotherValue = get(anotherAtom)
      }
    })

Comparison with useEffect

Component Side Effects

useEffect is a React Hook that lets you synchronize a component with an external system.

Hooks are functions that let you “hook into” React state and lifecycle features from function components. They are a way to reuse, but not centralize, stateful logic. Each call to a hook has a completely isolated state. This isolation can be referred to as component-scoped. For synchronizing component props and state with a Jotai atom, you should use the useEffect hook.

Global Side Effects

For setting up global side-effects, deciding between useEffect and atomEffect comes down to developer preference. Whether you prefer to build this logic directly into the component or build this logic into the Jotai state model depends on what mental model you adopt.

atomEffects are more appropriate for modeling behavior in atoms. They are scoped to the store context rather than the component. This guarantees that a single effect will be used regardless of how many calls they have.

The same guarantee can be achieved with the useEffect hook if you ensure that the useEffect is idempotent.

atomEffects are distinguished from useEffect in a few other ways. They can directly react to atom state changes, are resistent to infinite loops, and can be mounted conditionally.

It's up to you

Both useEffect and atomEffect have their own advantages and applications. Your project's specific needs and your comfort level should guide your selection. Always lean towards an approach that gives you a smoother, more intuitive development experience. Happy coding!