Overview
effect(fn) runs fn immediately and re-runs it whenever any atom read inside fn changes. If fn returns a function, that cleanup runs before the next execution and when the effect is disposed.
The return value of effect() itself is a dispose function — calling it stops the effect permanently. Effects created in a component outer function are disposed automatically on unmount.
Re-runs are scheduled (batched via microtask), not synchronous — do not assume the effect has re-run immediately after atom.set().
effect vs on / watch
|
API
|
Deps
|
First run
|
|---|---|---|
effect(fn)
| Auto-tracked reads | Runs immediately on create; then on dep change. |
on(fn, deps)
| Explicit array | Does not run on create — only when a listed dep notifies. |
Reactive side effects
effect() auto-tracks every atom read inside it and re-runs when any of them change. The first log line appears on create.
Cleanup before re-run
Return a cleanup function — it runs before the next execution and on dispose/unmount. Re-runs are microtask-batched after set().