0
# Context and Provider
1
2
Context system for providing Styletron engine instances to styled components and hooks throughout the React component tree. The Provider component is essential for all Styletron React functionality.
3
4
## Capabilities
5
6
### Provider Component
7
8
Provides Styletron engine instance to all styled components and `useStyletron` hooks in the component tree.
9
10
```typescript { .api }
11
/**
12
* Provides Styletron engine instance to styled components and hooks
13
* @param props.children - React children that will have access to the engine
14
* @param props.value - Styletron engine instance (StandardEngine)
15
* @param props.debugAfterHydration - Enable debug mode after SSR hydration (optional)
16
* @param props.debug - Debug engine instance for development tools (optional)
17
*/
18
const Provider: React.ComponentType<{
19
children: React.ReactNode;
20
value: StandardEngine;
21
debugAfterHydration?: boolean;
22
debug?: DebugEngine;
23
}>;
24
```
25
26
**Basic Usage:**
27
28
```typescript
29
import React from "react";
30
import { Provider, styled } from "styletron-react";
31
import { Client } from "styletron-engine-atomic";
32
33
// Create Styletron engine
34
const engine = new Client();
35
36
const StyledButton = styled("button", {
37
backgroundColor: "blue",
38
color: "white",
39
padding: "8px 16px",
40
});
41
42
function App() {
43
return (
44
<Provider value={engine}>
45
<div>
46
<h1>My App</h1>
47
<StyledButton>Click me</StyledButton>
48
</div>
49
</Provider>
50
);
51
}
52
```
53
54
### Server-Side Rendering (SSR)
55
56
```typescript
57
import React from "react";
58
import { renderToString } from "react-dom/server";
59
import { Provider, styled } from "styletron-react";
60
import { Server } from "styletron-engine-atomic";
61
62
// Server-side engine
63
const engine = new Server();
64
65
const App = () => (
66
<Provider value={engine}>
67
<styled.div $style={{ color: "red" }}>
68
SSR Content
69
</styled.div>
70
</Provider>
71
);
72
73
// Render on server
74
const html = renderToString(<App />);
75
76
// Get generated CSS
77
const css = engine.getCss();
78
79
// Send both HTML and CSS to client
80
const fullHtml = `
81
<html>
82
<head>
83
<style>${css}</style>
84
</head>
85
<body>
86
<div id="root">${html}</div>
87
</body>
88
</html>
89
`;
90
```
91
92
### Client-Side Hydration
93
94
```typescript
95
import React from "react";
96
import { hydrateRoot } from "react-dom/client";
97
import { Provider, styled } from "styletron-react";
98
import { Client } from "styletron-engine-atomic";
99
100
// Client-side engine with SSR hydration
101
const engine = new Client({
102
hydrate: document.getElementsByTagName("style"),
103
});
104
105
const App = () => (
106
<Provider value={engine}>
107
<styled.div $style={{ color: "red" }}>
108
Hydrated Content
109
</styled.div>
110
</Provider>
111
);
112
113
// Hydrate on client
114
const container = document.getElementById("root");
115
hydrateRoot(container, <App />);
116
```
117
118
### Development Mode with Debug
119
120
```typescript
121
import React from "react";
122
import { Provider, styled, DebugEngine } from "styletron-react";
123
import { Client } from "styletron-engine-atomic";
124
125
const engine = new Client();
126
const debugEngine = new DebugEngine();
127
128
const StyledComponent = styled("div", {
129
padding: "16px",
130
backgroundColor: "lightblue",
131
});
132
133
function App() {
134
return (
135
<Provider
136
value={engine}
137
debug={debugEngine}
138
debugAfterHydration={false}
139
>
140
<StyledComponent>
141
Debug-enabled component
142
</StyledComponent>
143
</Provider>
144
);
145
}
146
```
147
148
### Multiple Providers
149
150
```typescript
151
import React from "react";
152
import { Provider, styled } from "styletron-react";
153
import { Client } from "styletron-engine-atomic";
154
155
// Different engines for different parts of the app
156
const mainEngine = new Client();
157
const isolatedEngine = new Client();
158
159
const MainButton = styled("button", { backgroundColor: "blue" });
160
const IsolatedButton = styled("button", { backgroundColor: "red" });
161
162
function App() {
163
return (
164
<Provider value={mainEngine}>
165
<div>
166
<h1>Main App</h1>
167
<MainButton>Main Button</MainButton>
168
169
{/* Nested provider with different engine */}
170
<Provider value={isolatedEngine}>
171
<div>
172
<h2>Isolated Section</h2>
173
<IsolatedButton>Isolated Button</IsolatedButton>
174
</div>
175
</Provider>
176
</div>
177
</Provider>
178
);
179
}
180
```
181
182
## Engine Types
183
184
### Standard Engine Interface
185
186
```typescript { .api }
187
interface StandardEngine {
188
/**
189
* Renders a style object to CSS class name
190
* @param styleObject - Style object to render
191
* @returns CSS class name string
192
*/
193
renderStyle(styleObject: StyleObject): string;
194
195
/**
196
* Renders keyframes animation to CSS
197
* @param keyframes - Keyframes object
198
* @returns Animation name string
199
*/
200
renderKeyframes(keyframes: KeyframesObject): string;
201
202
/**
203
* Renders font face declaration to CSS
204
* @param fontFace - Font face object
205
* @returns Font family name string
206
*/
207
renderFontFace(fontFace: FontFaceObject): string;
208
}
209
```
210
211
### Debug Engine
212
213
```typescript { .api }
214
class DebugEngine {
215
/**
216
* Creates debug information for styled components
217
* @param options - Debug options including stack information
218
* @returns Debug class name for development tools
219
*/
220
debug(options: {
221
stackInfo: {
222
stack: any;
223
message: any;
224
};
225
stackIndex: number;
226
}): string | undefined;
227
}
228
```
229
230
## Error Handling
231
232
### No Engine Provided
233
234
When no Provider is found in the component tree, Styletron React will use a no-op engine and show a warning in development mode:
235
236
```typescript
237
// This will trigger a warning in development
238
function ComponentWithoutProvider() {
239
const StyledDiv = styled("div", { color: "red" });
240
241
return <StyledDiv>No provider found</StyledDiv>;
242
// Warning: "Styletron Provider is not set up. Defaulting to no-op."
243
}
244
```
245
246
### Engine Compatibility
247
248
Ensure the engine implements the `StandardEngine` interface:
249
250
```typescript
251
import { Client, Server } from "styletron-engine-atomic";
252
253
// ✅ Compatible engines
254
const clientEngine = new Client();
255
const serverEngine = new Server();
256
257
// ❌ Incompatible - missing required methods
258
const invalidEngine = {
259
renderStyle: () => "class-name",
260
// Missing renderKeyframes and renderFontFace
261
};
262
```
263
264
## Provider Props
265
266
```typescript { .api }
267
interface ProviderProps {
268
/** React children components */
269
children: React.ReactNode;
270
271
/** Styletron engine instance implementing StandardEngine interface */
272
value: StandardEngine;
273
274
/**
275
* Enable debug mode after SSR hydration (optional)
276
* Useful for avoiding hydration mismatches in development
277
*/
278
debugAfterHydration?: boolean;
279
280
/**
281
* Debug engine instance for development tools (optional)
282
* Only used in development mode for debugging and devtools integration
283
*/
284
debug?: DebugEngine;
285
}
286
```
287
288
## Best Practices
289
290
### Single Provider Pattern
291
292
Use one Provider at the root of your application:
293
294
```typescript
295
// ✅ Recommended
296
function App() {
297
return (
298
<Provider value={engine}>
299
<Router>
300
<Routes>
301
<Route path="/" component={Home} />
302
<Route path="/about" component={About} />
303
</Routes>
304
</Router>
305
</Provider>
306
);
307
}
308
```
309
310
### Engine Initialization
311
312
Initialize engines outside of render functions:
313
314
```typescript
315
// ✅ Initialize outside component
316
const engine = new Client();
317
318
function App() {
319
return <Provider value={engine}>...</Provider>;
320
}
321
322
// ❌ Avoid initializing inside component
323
function App() {
324
const engine = new Client(); // Creates new engine on every render
325
return <Provider value={engine}>...</Provider>;
326
}
327
```
328
329
### Development vs Production
330
331
Use different configurations for development and production:
332
333
```typescript
334
const isDevelopment = process.env.NODE_ENV === "development";
335
336
const engine = new Client({
337
prefix: isDevelopment ? "dev_" : "",
338
});
339
340
const debugEngine = isDevelopment ? new DebugEngine() : undefined;
341
342
function App() {
343
return (
344
<Provider
345
value={engine}
346
debug={debugEngine}
347
debugAfterHydration={isDevelopment}
348
>
349
<AppContent />
350
</Provider>
351
);
352
}
353
```