0
# Static Rendering Support
1
2
Server-side rendering utilities that control reactive behavior in SSR environments. These APIs ensure components render correctly on the server without creating MobX reactions or memory leaks.
3
4
## Capabilities
5
6
### enableStaticRendering Function
7
8
Enables or disables static rendering mode for server-side rendering environments. When enabled, observer components will not create MobX reactions and will render only once.
9
10
```typescript { .api }
11
/**
12
* Enables or disables static rendering mode for SSR environments
13
* @param enable - True to enable static rendering, false to disable
14
*/
15
function enableStaticRendering(enable: boolean): void;
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import { enableStaticRendering } from "mobx-react-lite";
22
23
// Enable static rendering on the server
24
if (typeof window === "undefined") {
25
enableStaticRendering(true);
26
}
27
28
// In Next.js _app.tsx or similar SSR setup
29
import { enableStaticRendering } from "mobx-react-lite";
30
31
// Enable static rendering for server-side rendering
32
enableStaticRendering(typeof window === "undefined");
33
34
export default function App({ Component, pageProps }) {
35
return <Component {...pageProps} />;
36
}
37
38
// In a Node.js server rendering setup
39
import { renderToString } from "react-dom/server";
40
import { enableStaticRendering } from "mobx-react-lite";
41
42
// Enable before server rendering
43
enableStaticRendering(true);
44
45
const html = renderToString(<App />);
46
47
// Optionally disable after rendering if reusing the same process
48
enableStaticRendering(false);
49
```
50
51
### isUsingStaticRendering Function
52
53
Returns whether static rendering mode is currently enabled. Useful for debugging or conditional logic based on rendering environment.
54
55
```typescript { .api }
56
/**
57
* Returns the current static rendering mode status
58
* @returns True if static rendering is enabled, false otherwise
59
*/
60
function isUsingStaticRendering(): boolean;
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { isUsingStaticRendering } from "mobx-react-lite";
67
68
// Conditional behavior based on rendering mode
69
const MyComponent = observer(() => {
70
const store = useStore();
71
72
// Only set up subscriptions on the client
73
useEffect(() => {
74
if (!isUsingStaticRendering()) {
75
const subscription = subscribeToUpdates(store);
76
return () => subscription.unsubscribe();
77
}
78
}, [store]);
79
80
return <div>{store.data}</div>;
81
});
82
83
// Debug logging
84
console.log("Static rendering enabled:", isUsingStaticRendering());
85
86
// Conditional API calls
87
const DataComponent = observer(() => {
88
const store = useLocalObservable(() => ({
89
data: null,
90
loading: false,
91
92
async loadData() {
93
if (isUsingStaticRendering()) {
94
// Skip async operations during SSR
95
return;
96
}
97
98
this.loading = true;
99
try {
100
this.data = await fetchData();
101
} finally {
102
this.loading = false;
103
}
104
}
105
}));
106
107
useEffect(() => {
108
store.loadData();
109
}, [store]);
110
111
return (
112
<div>
113
{store.loading ? "Loading..." : store.data}
114
</div>
115
);
116
});
117
```
118
119
### useStaticRendering Function (Deprecated)
120
121
Deprecated wrapper around `enableStaticRendering`. Use `enableStaticRendering` instead.
122
123
```typescript { .api }
124
/**
125
* @deprecated Use enableStaticRendering instead
126
* Enables or disables static rendering mode
127
* @param enable - True to enable static rendering, false to disable
128
*/
129
function useStaticRendering(enable: boolean): void;
130
```
131
132
## Important Notes
133
134
### SSR Behavior
135
136
When static rendering is enabled:
137
138
- **No reactions**: Observer components don't create MobX reactions
139
- **Single render**: Components render exactly once without re-rendering on observable changes
140
- **Memory efficiency**: No memory leaks from reactions that would never be cleaned up on server
141
- **Synchronous rendering**: All rendering is synchronous, no async observable updates
142
- **Cleanup automatic**: No manual cleanup required since no reactions are created
143
144
### Common SSR Patterns
145
146
```typescript
147
// Typical SSR setup pattern
148
import { enableStaticRendering } from "mobx-react-lite";
149
150
// Enable static rendering for server-side
151
if (typeof window === "undefined") {
152
enableStaticRendering(true);
153
}
154
155
// Universal component that works on both server and client
156
const UniversalComponent = observer(() => {
157
const store = useLocalObservable(() => ({
158
data: getInitialData(), // Should be synchronous for SSR
159
hydrated: false,
160
161
hydrate() {
162
if (!isUsingStaticRendering()) {
163
this.hydrated = true;
164
// Perform client-side initialization
165
}
166
}
167
}));
168
169
useEffect(() => {
170
store.hydrate();
171
}, [store]);
172
173
return (
174
<div>
175
<div>Data: {store.data}</div>
176
{store.hydrated && <div>Client-side content</div>}
177
</div>
178
);
179
});
180
```
181
182
### Integration with SSR Frameworks
183
184
**Next.js:**
185
```typescript
186
// pages/_app.tsx
187
import { enableStaticRendering } from "mobx-react-lite";
188
189
enableStaticRendering(typeof window === "undefined");
190
```
191
192
**Gatsby:**
193
```typescript
194
// gatsby-ssr.js
195
import { enableStaticRendering } from "mobx-react-lite";
196
197
export const onRenderBody = () => {
198
enableStaticRendering(true);
199
};
200
```
201
202
**Custom Server:**
203
```typescript
204
import express from "express";
205
import { renderToString } from "react-dom/server";
206
import { enableStaticRendering } from "mobx-react-lite";
207
208
const app = express();
209
210
app.get("*", (req, res) => {
211
enableStaticRendering(true);
212
213
const html = renderToString(<App />);
214
215
res.send(`
216
<!DOCTYPE html>
217
<html>
218
<body>
219
<div id="root">${html}</div>
220
<script src="/bundle.js"></script>
221
</body>
222
</html>
223
`);
224
});
225
```
226
227
### Performance Considerations
228
229
- **Server performance**: Static rendering eliminates the overhead of creating and managing MobX reactions on the server
230
- **Hydration**: Components will start creating reactions after hydration on the client
231
- **Memory usage**: Significantly reduces server memory usage by avoiding reaction creation
232
- **Rendering speed**: Faster server rendering since no observable dependency tracking occurs