Install
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
Usage
Usage With React
Pass the store to bothobserve and the Provider to ensure the effect is mounted to the correct store.
atomEffect
atomEffect creates an atom for declaring side effects that react to state changes when mounted.
Signature
Usage
withAtomEffect
withAtomEffect binds an effect to a clone of the target atom. The effect is active while the cloned atom is mounted.
Signature
Usage
Dependency Management
Aside from mount events, the effect runs when any of its dependencies change value.- Sync: All atoms accessed with
getinside the effect are added to the atom’s dependencies. - Async: Asynchronous
getcalls do not add dependencies. - Cleanup:
getcalls in cleanup do not add dependencies. - Dependency Map Recalculation: Dependencies are recalculated on every run.
Effect Behavior
- Executes Synchronously:
effectruns synchronous in the current task after synchronous evaluations complete. - Batched Updates: Multiple synchronous updates are batched as a single atomic transaction.
- Resistant to Infinite Loops:
atomEffectavoids rerunning when it updates a value that it is watching. - Cleanup Function: The cleanup function is invoked on unmount or before re-evaluation.
- Idempotency:
atomEffectruns once per state change, regardless of how many times it is referenced. - Conditionally Running Effects:
atomEffectonly runs when mounted. - Supports Peek: Use
get.peekto read atom data without subscribing. - Supports Recursion: Recursion is supported with
set.recursebut not in cleanup.