Understand effect execution and behavior
mainEffects in jotai-effect follow these behaviors:
- Synchronous Execution: Effects run synchronously in the current task after synchronous evaluations complete.
- Batched Updates: Multiple synchronous updates are batched into a single atomic transaction.
- Infinite Loop Resistance:
atomEffectavoids re-running if it updates a value that it is currently watching. - Idempotency: An effect runs exactly once per state change, regardless of how many times the effect atom is referenced.
- Cleanup: A returned function is invoked on unmount or before the effect re-evaluates due to dependency changes.
- Recursion: You can use
set.recurseto trigger updates, but recursion is not supported within cleanup functions.
// Example of loop resistance
atomEffect((get, set) => {
get(countAtom)
set(countAtom, (value) => value + 1) // Will not loop
})
// Example of recursion
atomEffect((get, set) => {
const count = get(countAtom)
if (count % 10 === 0) return
set.recurse(countAtom, (value) => value + 1)
})