0
# React Hooks
1
2
Hook-based API for direct CSS class generation and integration with React functional components. Provides direct access to the Styletron engine for dynamic styling without creating styled components.
3
4
## Capabilities
5
6
### useStyletron Hook
7
8
Returns a CSS function that generates class names from style objects, enabling direct style application within functional components.
9
10
```typescript { .api }
11
/**
12
* Returns a CSS function that generates class names from style objects
13
* @returns Tuple containing the css function
14
*/
15
function useStyletron(): [(style: StyleObject) => string];
16
```
17
18
**Usage Examples:**
19
20
```typescript
21
import React, { useState } from "react";
22
import { useStyletron, Provider } from "styletron-react";
23
24
function DynamicComponent() {
25
const [css] = useStyletron();
26
const [isActive, setIsActive] = useState(false);
27
28
// Generate class names dynamically
29
const buttonClass = css({
30
padding: "8px 16px",
31
backgroundColor: isActive ? "green" : "blue",
32
color: "white",
33
border: "none",
34
borderRadius: "4px",
35
cursor: "pointer",
36
":hover": {
37
opacity: 0.8,
38
},
39
});
40
41
const containerClass = css({
42
display: "flex",
43
gap: "16px",
44
padding: "20px",
45
});
46
47
return (
48
<div className={containerClass}>
49
<button
50
className={buttonClass}
51
onClick={() => setIsActive(!isActive)}
52
>
53
{isActive ? "Active" : "Inactive"}
54
</button>
55
</div>
56
);
57
}
58
59
// Must be wrapped with Provider
60
function App() {
61
return (
62
<Provider value={engine}>
63
<DynamicComponent />
64
</Provider>
65
);
66
}
67
```
68
69
### Advanced Hook Usage
70
71
```typescript
72
import React, { useMemo } from "react";
73
import { useStyletron } from "styletron-react";
74
75
function OptimizedComponent({ theme, size }: {
76
theme: "light" | "dark";
77
size: "small" | "large";
78
}) {
79
const [css] = useStyletron();
80
81
// Memoize style objects for performance
82
const buttonStyles = useMemo(() => ({
83
padding: size === "large" ? "12px 24px" : "8px 16px",
84
fontSize: size === "large" ? "16px" : "14px",
85
backgroundColor: theme === "dark" ? "#333" : "#f0f0f0",
86
color: theme === "dark" ? "white" : "black",
87
border: `1px solid ${theme === "dark" ? "#555" : "#ccc"}`,
88
borderRadius: "4px",
89
}), [theme, size]);
90
91
const buttonClass = css(buttonStyles);
92
93
return (
94
<button className={buttonClass}>
95
Themed Button
96
</button>
97
);
98
}
99
```
100
101
### Conditional Styling
102
103
```typescript
104
import React from "react";
105
import { useStyletron } from "styletron-react";
106
107
function ConditionalComponent({
108
variant,
109
disabled,
110
fullWidth
111
}: {
112
variant: "primary" | "secondary";
113
disabled?: boolean;
114
fullWidth?: boolean;
115
}) {
116
const [css] = useStyletron();
117
118
// Build styles conditionally
119
const baseStyles = {
120
padding: "8px 16px",
121
border: "none",
122
borderRadius: "4px",
123
cursor: disabled ? "not-allowed" : "pointer",
124
opacity: disabled ? 0.6 : 1,
125
width: fullWidth ? "100%" : "auto",
126
};
127
128
const variantStyles = variant === "primary"
129
? { backgroundColor: "blue", color: "white" }
130
: { backgroundColor: "gray", color: "black" };
131
132
const buttonClass = css({
133
...baseStyles,
134
...variantStyles,
135
});
136
137
return (
138
<button className={buttonClass} disabled={disabled}>
139
Conditional Button
140
</button>
141
);
142
}
143
```
144
145
### Combining with className
146
147
```typescript
148
import React from "react";
149
import { useStyletron } from "styletron-react";
150
151
function CombinedClassComponent({ className }: { className?: string }) {
152
const [css] = useStyletron();
153
154
const dynamicClass = css({
155
padding: "16px",
156
backgroundColor: "lightblue",
157
borderRadius: "8px",
158
});
159
160
// Combine generated class with external className
161
const combinedClassName = className
162
? `${className} ${dynamicClass}`
163
: dynamicClass;
164
165
return (
166
<div className={combinedClassName}>
167
Combined Styling
168
</div>
169
);
170
}
171
172
// Usage
173
<CombinedClassComponent className="external-styles" />
174
```
175
176
### Media Queries and Pseudo-selectors
177
178
```typescript
179
import React from "react";
180
import { useStyletron } from "styletron-react";
181
182
function ResponsiveComponent() {
183
const [css] = useStyletron();
184
185
const responsiveClass = css({
186
padding: "16px",
187
backgroundColor: "white",
188
borderRadius: "8px",
189
boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
190
":hover": {
191
boxShadow: "0 4px 8px rgba(0,0,0,0.15)",
192
transform: "translateY(-2px)",
193
},
194
":focus": {
195
outline: "2px solid blue",
196
outlineOffset: "2px",
197
},
198
"@media (max-width: 768px)": {
199
padding: "8px",
200
borderRadius: "4px",
201
},
202
"@media (max-width: 480px)": {
203
padding: "4px",
204
},
205
});
206
207
return (
208
<div className={responsiveClass} tabIndex={0}>
209
Responsive Component
210
</div>
211
);
212
}
213
```
214
215
## Performance Considerations
216
217
### Memoization
218
219
Use `useMemo` to prevent unnecessary style recalculations:
220
221
```typescript
222
import React, { useMemo } from "react";
223
import { useStyletron } from "styletron-react";
224
225
function PerformantComponent({ color, size }: {
226
color: string;
227
size: number;
228
}) {
229
const [css] = useStyletron();
230
231
// Memoize expensive style calculations
232
const styles = useMemo(() => ({
233
backgroundColor: color,
234
width: `${size}px`,
235
height: `${size}px`,
236
borderRadius: "50%",
237
// ... complex calculations
238
}), [color, size]);
239
240
const className = css(styles);
241
242
return <div className={className} />;
243
}
244
```
245
246
### Style Extraction
247
248
Extract static styles outside component for better performance:
249
250
```typescript
251
import React from "react";
252
import { useStyletron } from "styletron-react";
253
254
// Static styles defined outside component
255
const STATIC_STYLES = {
256
container: {
257
display: "flex",
258
flexDirection: "column",
259
gap: "16px",
260
},
261
header: {
262
fontSize: "24px",
263
fontWeight: "bold",
264
marginBottom: "8px",
265
},
266
} as const;
267
268
function StaticStyledComponent() {
269
const [css] = useStyletron();
270
271
const containerClass = css(STATIC_STYLES.container);
272
const headerClass = css(STATIC_STYLES.header);
273
274
return (
275
<div className={containerClass}>
276
<h1 className={headerClass}>Title</h1>
277
<p>Content</p>
278
</div>
279
);
280
}
281
```
282
283
## Types
284
285
```typescript { .api }
286
type StyleObject = {
287
[property: string]: string | number | StyleObject;
288
// CSS properties
289
display?: string;
290
padding?: string | number;
291
margin?: string | number;
292
backgroundColor?: string;
293
color?: string;
294
// Pseudo-selectors
295
":hover"?: StyleObject;
296
":focus"?: StyleObject;
297
":active"?: StyleObject;
298
":disabled"?: StyleObject;
299
// Media queries
300
"@media (max-width: 768px)"?: StyleObject;
301
"@media (min-width: 769px)"?: StyleObject;
302
// ... other CSS properties and selectors
303
};
304
```