undoRedo() helper function adds undo/redo capabilities to any observable. It tracks changes, manages history, and provides observables to monitor the number of available undo/redo operations.
Basic Usage
Type Signature
Return Value
The function returns an object with:undo()- Undo the last changeredo()- Redo the previously undone changeundos$- Observable with the number of available undosredos$- Observable with the number of available redosgetHistory()- Get the complete history array
Tracking Available Operations
History Limit
Limit the number of undo steps to conserve memory:How It Works
Initial Snapshot
The first change captures the initial value:History Branching
Making changes after undo deletes the redo history:Batched Changes
Batched changes are stored as a single history entry:Ignoring Sync/Persist Changes
Changes from sync or persistence are automatically ignored:React Integration
Use the observables to enable/disable UI buttons:jsx
Multiple Properties
Undo/redo works with complex objects:Accessing History
Get the full history array:Deep Cloning
History snapshots are deep cloned to prevent reference issues:Use Cases
Text Editor
Drawing App
Form with Undo
Configuration Editor
Edge Cases
Undo at Beginning
Redo at End
No Limit
Without a limit, history grows indefinitely:Best Practices
- Set a reasonable limit: Prevents memory issues with long-running apps
- Use batching: Group related changes to create meaningful undo steps
- Monitor available operations: Disable undo/redo buttons when unavailable
- Consider performance: Large objects in history can impact memory
- Handle edge cases: Test behavior at history boundaries
Performance Considerations
- Deep cloning: Each change clones the entire object - keep undo targets focused
- Memory usage: History grows with changes - use
limitoption - Batching: Reduces history entries and improves performance
Related
- trackHistory() - Track changes without undo/redo
- batch() - Group multiple changes
- onChange() - Listen to changes