0
# Component Observers
1
2
Core functionality for making React components reactive to MobX observable changes. The observer pattern automatically tracks observable access during render and triggers re-renders when any accessed observables change.
3
4
## Capabilities
5
6
### Observer Function
7
8
Higher-order component that wraps functional components to make them reactive to MobX observables. Automatically applies React.memo for performance optimization.
9
10
```typescript { .api }
11
/**
12
* Converts a React functional component into a reactive component
13
* @param baseComponent - The functional component to make reactive
14
* @param options - Optional configuration for forwardRef behavior
15
* @returns Reactive component that re-renders when observables change
16
*/
17
function observer<P extends object>(
18
baseComponent: React.FunctionComponent<P>,
19
options?: IObserverOptions
20
): React.FunctionComponent<P>;
21
22
// ForwardRef support
23
function observer<P extends object, TRef = {}>(
24
baseComponent: React.ForwardRefRenderFunction<TRef, P>,
25
options: IObserverOptions & { forwardRef: true }
26
): React.MemoExoticComponent<
27
React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>
28
>;
29
30
// ForwardRefExoticComponent support
31
function observer<P extends object, TRef = {}>(
32
baseComponent: React.ForwardRefExoticComponent<
33
React.PropsWithoutRef<P> & React.RefAttributes<TRef>
34
>
35
): React.MemoExoticComponent<
36
React.ForwardRefExoticComponent<React.PropsWithoutRef<P> & React.RefAttributes<TRef>>
37
>;
38
39
interface IObserverOptions {
40
readonly forwardRef?: boolean;
41
}
42
```
43
44
**Usage Examples:**
45
46
```typescript
47
import { observer } from "mobx-react-lite";
48
import { observable } from "mobx";
49
50
// Basic observer component
51
const UserProfile = observer(({ userId }: { userId: string }) => {
52
const store = useUserStore();
53
const user = store.getUser(userId);
54
55
return (
56
<div>
57
<h1>{user.name}</h1>
58
<p>Email: {user.email}</p>
59
</div>
60
);
61
});
62
63
// Observer with forwardRef
64
const FancyInput = observer(React.forwardRef<HTMLInputElement, Props>(
65
({ value, onChange }, ref) => {
66
return <input ref={ref} value={value} onChange={onChange} />;
67
}
68
));
69
70
// Alternative forwardRef syntax (deprecated)
71
const FancyInputAlt = observer(
72
(props: Props, ref: React.Ref<HTMLInputElement>) => {
73
return <input ref={ref} {...props} />;
74
},
75
{ forwardRef: true }
76
);
77
```
78
79
### Observer Component
80
81
React component that applies observer behavior to an anonymous region within your component. Can be used inside both class and function components.
82
83
```typescript { .api }
84
/**
85
* React component that makes its children reactive to observable changes
86
* @param props - Component props with children or render function
87
* @returns Reactive region that re-renders when observables change
88
*/
89
function Observer(props: IObserverProps): React.ReactElement | null;
90
91
interface IObserverProps {
92
/** Function returning React element to render */
93
children?(): React.ReactElement | null;
94
/** Alternative render function (same as children) */
95
render?(): React.ReactElement | null;
96
}
97
```
98
99
**Usage Examples:**
100
101
```typescript
102
import { Observer } from "mobx-react-lite";
103
import { observable } from "mobx";
104
105
// Using Observer with children function
106
const App = () => {
107
const [store] = useState(() => observable({ count: 0 }));
108
109
return (
110
<div>
111
<h1>My App</h1>
112
<Observer>
113
{() => <div>Reactive count: {store.count}</div>}
114
</Observer>
115
<button onClick={() => store.count++}>
116
Increment
117
</button>
118
</div>
119
);
120
};
121
122
// Using Observer with render prop
123
const Dashboard = () => {
124
const store = useStore();
125
126
return (
127
<div>
128
<Observer render={() =>
129
<div className={store.theme}>
130
User: {store.currentUser.name}
131
</div>
132
} />
133
</div>
134
);
135
};
136
137
// Using Observer inside class components
138
class LegacyComponent extends React.Component {
139
render() {
140
return (
141
<div>
142
<Observer>
143
{() => <div>Reactive data: {this.props.store.data}</div>}
144
</Observer>
145
</div>
146
);
147
}
148
}
149
```
150
151
## Important Notes
152
153
### Observer Behavior
154
155
- **Automatic tracking**: Observer automatically tracks which observables are accessed during render
156
- **Batched updates**: Updates are batched using React's built-in batching mechanisms
157
- **Memory management**: Reactions are automatically disposed when components unmount
158
- **Error boundaries**: Exceptions during rendering are properly re-thrown to error boundaries
159
- **Static rendering**: In SSR mode, observer components render normally without creating reactions
160
161
### Common Patterns
162
163
- **Wrap entire components**: Use `observer()` to wrap your entire functional component
164
- **Selective observation**: Use `<Observer>` for specific reactive regions within larger components
165
- **Avoid double wrapping**: Don't wrap observer components with React.memo (observer already applies memo)
166
- **ForwardRef integration**: Use React.forwardRef() directly rather than the deprecated forwardRef option
167
168
### Performance Considerations
169
170
- Observer automatically applies React.memo with shallow comparison
171
- Only components that access observables during render will re-render
172
- Unused observables won't trigger re-renders even if they change
173
- Observers batch updates automatically for optimal performance