Overview
Theeffect() function creates a reactive side effect that automatically tracks dependencies and handles cleanup. It’s similar to computed() but designed specifically for running side effects. Effects automatically subscribe to any atoms read within the callback and cancel ongoing async operations when dependencies change or the effect is stopped.
Import
Signature
Parameters
() => T
required
The function to run as a side effect. It can be synchronous or asynchronous. Any atoms read inside this function will become dependencies, and the effect will re-run when they change.
string
Optional name for the effect. Useful for debugging and dev tools. If not provided, an auto-generated name will be used.
Returns
Effect<T>
An effect instance with the following interface:
Examples
Basic Effect
Async Effects with Polling
Conditional Dependencies
Effect with Cleanup
Manual Unsubscribe
Effect in Component Context
Multiple Dependencies
Error Handling in Effects
Effect with Suspense
Type Information
Effect Interface
Unsubscribe Type
Key Characteristics
- Automatic Subscription: Effects automatically subscribe on creation
- Dependency Tracking: Atoms read within the effect become dependencies
- Auto-Cleanup: When dependencies change, ongoing async operations are cancelled
- Abort Handling: Uses
wrap()with abort controllers to cancel async operations - Error Safety: Unhandled errors are thrown, but abort errors are silently ignored
- Context-Aware: Effects are automatically cleaned up in managed contexts
Best Practices
- Use
wrap()for async operations: Always wrap promises withwrap()to enable automatic cancellation - Handle abort errors: Check for
isAbort(error)in catch blocks to distinguish cancellation from real errors - Keep effects focused: Each effect should handle one specific side effect
- Conditional dependencies: Use conditional logic to control which atoms are tracked
- Manual cleanup: Only call
unsubscribe()when managing effects outside of component contexts
Related
- computed() - Create derived state (effects are built on computed)
- atom() - Create state that effects can depend on
- action() - Create logic containers
- wrap() - Wrap promises for automatic cancellation
- withAbort() - Extension used internally by effects