0
# Advanced Features
1
2
Advanced configuration and utilities including observer batching, memory management, and deprecated APIs for migration purposes. These features provide fine-grained control over MobX React Lite behavior and compatibility.
3
4
## Capabilities
5
6
### Observer Batching
7
8
Controls how MobX reactions are scheduled and batched with React's update mechanisms. This ensures optimal performance by coordinating MobX updates with React's batching system.
9
10
```typescript { .api }
11
/**
12
* Configures MobX reaction scheduler for batching updates with React
13
* @param reactionScheduler - Batching function, typically from React DOM or React Native
14
*/
15
function observerBatching(reactionScheduler: any): void;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { observerBatching } from "mobx-react-lite";
22
import { unstable_batchedUpdates } from "react-dom";
23
24
// Manual batching configuration (usually automatic)
25
observerBatching(unstable_batchedUpdates);
26
27
// React Native batching
28
import { unstable_batchedUpdates } from "react-native";
29
observerBatching(unstable_batchedUpdates);
30
31
// Custom batching function
32
observerBatching((callback) => {
33
// Custom batching logic
34
console.log("Batching MobX reaction");
35
callback();
36
});
37
38
// Disable batching (not recommended)
39
observerBatching(null);
40
```
41
42
### Observer Batch Status (Deprecated)
43
44
Returns whether observer batching is enabled. This function is deprecated and always returns true.
45
46
```typescript { .api }
47
/**
48
* @deprecated Always returns true
49
* Returns whether observer batching is enabled
50
* @returns Always true in current implementation
51
*/
52
function isObserverBatched(): boolean;
53
```
54
55
### Memory Management
56
57
Utilities for managing internal timers and finalization registry used by the observer system.
58
59
```typescript { .api }
60
/**
61
* Clears internal finalization timers immediately
62
* Useful for testing or manual memory management
63
*/
64
function clearTimers(): void;
65
```
66
67
**Usage Examples:**
68
69
```typescript
70
import { clearTimers } from "mobx-react-lite";
71
72
// Clear timers in test cleanup
73
afterEach(() => {
74
clearTimers();
75
});
76
77
// Manual cleanup before app shutdown
78
window.addEventListener("beforeunload", () => {
79
clearTimers();
80
});
81
82
// In test environments
83
if (process.env.NODE_ENV === "test") {
84
// Clear timers between tests to prevent interference
85
beforeEach(() => {
86
clearTimers();
87
});
88
}
89
```
90
91
### Deprecated useObserver Hook
92
93
Low-level hook that provides observer functionality with manual control. This is deprecated in favor of the `observer` HOC or `<Observer>` component.
94
95
```typescript { .api }
96
/**
97
* @deprecated Use <Observer>{fn}</Observer> instead or wrap component with observer
98
* Manually creates an observer region within a component
99
* @param fn - Function to track for observable access
100
* @param baseComponentName - Name for debugging purposes
101
* @returns Result of the tracked function
102
*/
103
function useObserver<T>(fn: () => T, baseComponentName?: string): T;
104
```
105
106
**Migration Examples:**
107
108
```typescript
109
// Old approach (deprecated)
110
const MyComponent = () => {
111
const store = useStore();
112
113
return useObserver(() => (
114
<div>
115
<h1>{store.title}</h1>
116
<p>{store.description}</p>
117
</div>
118
), "MyComponent");
119
};
120
121
// New approach with Observer component
122
const MyComponent = () => {
123
const store = useStore();
124
125
return (
126
<Observer>
127
{() => (
128
<div>
129
<h1>{store.title}</h1>
130
<p>{store.description}</p>
131
</div>
132
)}
133
</Observer>
134
);
135
};
136
137
// Best approach with observer HOC
138
const MyComponent = observer(() => {
139
const store = useStore();
140
141
return (
142
<div>
143
<h1>{store.title}</h1>
144
<p>{store.description}</p>
145
</div>
146
);
147
});
148
```
149
150
## Internal Implementation Details
151
152
### Batching Files
153
154
MobX React Lite provides several batching configuration files for different environments:
155
156
- `batchingForReactDom.js` - React DOM batching configuration
157
- `batchingForReactNative.js` - React Native batching configuration
158
- `batchingOptOut.js` - Disables batching entirely
159
160
These files can be imported directly to configure batching behavior:
161
162
```javascript
163
// Import specific batching configuration
164
import "mobx-react-lite/batchingForReactDom";
165
166
// Or for React Native
167
import "mobx-react-lite/batchingForReactNative";
168
169
// Or to opt out of batching
170
import "mobx-react-lite/batchingOptOut";
171
```
172
173
### Development vs Production
174
175
Several features behave differently in development vs production:
176
177
- **Deprecation warnings**: Only shown in development mode
178
- **PropTypes validation**: Only active in development for Observer component
179
- **Debug information**: Additional debugging info available in development
180
- **Error messages**: More detailed error messages in development
181
182
```typescript
183
// Development-only warnings example
184
if (process.env.NODE_ENV !== "production") {
185
console.warn("[mobx-react-lite] Development warning message");
186
}
187
```
188
189
## Important Notes
190
191
### Batching Behavior
192
193
- **Automatic configuration**: MobX React Lite automatically configures batching on import
194
- **React 18 compatibility**: Works with both legacy and concurrent React features
195
- **Custom schedulers**: Advanced users can provide custom batching functions
196
- **Performance impact**: Proper batching significantly improves performance with multiple observable changes
197
198
### Memory Management
199
200
- **Automatic cleanup**: Components automatically clean up reactions on unmount
201
- **Finalization registry**: Modern browsers use FinalizationRegistry for additional cleanup
202
- **Manual control**: `clearTimers()` provides manual control over cleanup timing
203
- **Test environments**: Important to clear timers between tests to prevent interference
204
205
### Migration Path
206
207
For codebases upgrading from older versions:
208
209
1. **Replace useObserver**: Convert `useObserver` calls to `<Observer>` component or `observer` HOC
210
2. **Update useLocalStore**: Migrate from `useLocalStore` to `useLocalObservable`
211
3. **Remove useAsObservableSource**: Replace with `useEffect` synchronization pattern
212
4. **Update static rendering**: Use `enableStaticRendering` instead of `useStaticRendering`
213
214
### Performance Optimization
215
216
- **Batching**: Ensure proper batching configuration for your React environment
217
- **Memory cleanup**: Use `clearTimers()` in test environments to prevent memory leaks
218
- **Observer granularity**: Use `<Observer>` for fine-grained reactive regions in large components
219
- **Static rendering**: Enable static rendering for SSR to avoid unnecessary server-side reactions