Skip to main content

Overview

The withChangeHook 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 value
  • prevState: The previous state value (undefined on first change)

When to Use

Use withChangeHook 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
Don’t use when:
  • In dynamic features, like from computed factories (use take or effect with ifChanged instead)
  • When a regular computed dependency would suffice
  • For connection/disconnection events (use withConnectHook instead)

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