Overview
ThewithChangeHook extension executes a callback whenever the target atom’s state changes. It’s essential for creating stable, declarative connections between independent modules or features.
The hook fires in the “Hooks” phase of Reatom’s lifecycle (after Updates, before Computations), making it perfect for triggering side effects or synchronizing state across module boundaries.
Type Signature
Parameters
function
required
Callback fired when state changes. Only fires when the state actually changes (referential inequality check via
Object.is).Parameters:state: The new state valueprevState: The previous state value (undefined on first change)
When to Use
UsewithChangeHook when:
- Creating stable connections between features that shouldn’t depend on each other directly
- Triggering validation when a field’s value or state changes
- Syncing derived state in response to source state changes
- Managing side effects like DOM updates or analytics based on state changes
- Coordinating behavior across module boundaries without coupling them
- In dynamic features, like from computed factories (use
takeoreffectwithifChangedinstead) - When a regular computed dependency would suffice
- For connection/disconnection events (use
withConnectHookinstead)
Examples
Basic State Changes
Theme Management
Analytics Tracking
Form Field Validation
Sync to LocalStorage
Computed State Changes
Type-Safe Callbacks
Advanced Usage
Dynamic Hook Addition
Conditional Side Effects
Cross-Module Coordination
Debounced Side Effects
Comparison with Other Hooks
withChangeHook vs withCallHook
withChangeHook vs withConnectHook
Use Cases
Form Auto-Save
URL Sync
Undo/Redo History
Real-time Sync
Related
- withCallHook - React to action calls
- withConnectHook - React to subscription lifecycle
- addChangeHook - Dynamically add/remove hooks