observer higher-order component (HOC) wraps React components to automatically track observable access and re-render only when tracked observables change.
Overview
observer eliminates the need to manually call hooks for every observable you want to track. Simply wrap your component with observer and call .get() on any observable - the component will automatically re-render when those observables change.
Basic Usage
- Function Component
- Arrow Function
- With TypeScript
How It Works
When you wrap a component withobserver:
- The component function is wrapped in a tracking context
- Any
.get()calls on observables are automatically tracked - When tracked observables change, the component re-renders
- Only the observables actually accessed during render are tracked
With Memo
Theobserver HOC automatically wraps components with React.memo, so you don’t need to do it manually:
With forwardRef
observer works seamlessly with forwardRef:
Performance Benefits
Fine-Grained Tracking
observer only re-renders when the specific observables accessed during render change:
Prevents Unnecessary Renders
Common Patterns
Global State
Computed Values
Conditional Rendering
Combining with Hooks
observer works perfectly with Legend-State hooks:
Alternative: reactiveObserver
reactiveObserver combines observer with reactive, allowing both automatic tracking and reactive props:
Best Practices
Performance Comparison
Here’s howobserver compares to manual hooks:
observer is more concise.
See Also
React Hooks
Learn about useObservable, useSelector, and more
Reactive Components
Pass observables as props with $ prefix
Fine-Grained Rendering
Advanced patterns for optimal performance