npm-react

Description
React is a JavaScript library for building user interfaces with declarative, component-based architecture.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-react@18.3.0

builtin-components.md docs/

1
# Built-in Components
2
3
React provides several built-in components for layout, performance optimization, and development features. These special components enable advanced React patterns and help with debugging and performance.
4
5
## Capabilities
6
7
### Fragment
8
9
Groups multiple elements without adding an extra DOM node.
10
11
```javascript { .api }
12
/**
13
* Groups children without creating DOM wrapper
14
*/
15
const Fragment: ExoticComponent<{ children?: ReactNode }>;
16
```
17
18
**Usage Examples:**
19
20
```javascript
21
import React, { Fragment } from 'react';
22
23
// Using Fragment component
24
function UserInfo({ user }) {
25
return (
26
<Fragment>
27
<h2>{user.name}</h2>
28
<p>{user.email}</p>
29
<p>{user.role}</p>
30
</Fragment>
31
);
32
}
33
34
// Using short syntax
35
function UserInfo({ user }) {
36
return (
37
<>
38
<h2>{user.name}</h2>
39
<p>{user.email}</p>
40
<p>{user.role}</p>
41
</>
42
);
43
}
44
45
// With key prop (useful in lists)
46
function ItemList({ items }) {
47
return (
48
<ul>
49
{items.map(item => (
50
<Fragment key={item.id}>
51
<li>{item.name}</li>
52
<li className="description">{item.description}</li>
53
</Fragment>
54
))}
55
</ul>
56
);
57
}
58
59
// Conditional fragments
60
function ConditionalContent({ showDetails, user }) {
61
return (
62
<div>
63
<h1>Welcome</h1>
64
{showDetails && (
65
<Fragment>
66
<p>User: {user.name}</p>
67
<p>Last login: {user.lastLogin}</p>
68
<p>Status: {user.status}</p>
69
</Fragment>
70
)}
71
</div>
72
);
73
}
74
```
75
76
### StrictMode
77
78
Enables additional checks and warnings for development.
79
80
```javascript { .api }
81
/**
82
* Enables additional development checks and warnings
83
*/
84
const StrictMode: ExoticComponent<{ children?: ReactNode }>;
85
```
86
87
**Usage Examples:**
88
89
```javascript
90
import React, { StrictMode } from 'react';
91
92
// Wrap entire app in StrictMode
93
function App() {
94
return (
95
<StrictMode>
96
<Header />
97
<MainContent />
98
<Footer />
99
</StrictMode>
100
);
101
}
102
103
// Wrap specific components for stricter checks
104
function DevelopmentApp() {
105
return (
106
<div>
107
<Header />
108
<StrictMode>
109
{/* This section will have additional checks */}
110
<ExperimentalFeature />
111
<NewComponent />
112
</StrictMode>
113
<Footer />
114
</div>
115
);
116
}
117
118
// StrictMode helps identify:
119
// - Components with unsafe lifecycles
120
// - Legacy string ref API usage
121
// - Deprecated findDOMNode usage
122
// - Unexpected side effects
123
// - Legacy context API
124
function ProblematicComponent() {
125
// StrictMode will warn about this deprecated lifecycle
126
UNSAFE_componentWillReceiveProps(nextProps) {
127
// This will trigger warnings in StrictMode
128
}
129
130
// StrictMode will help detect side effects by double-invoking
131
useEffect(() => {
132
// This effect should be idempotent
133
console.log('Effect running'); // Will log twice in StrictMode
134
}, []);
135
136
return <div>Component content</div>;
137
}
138
```
139
140
### Profiler
141
142
Measures performance of React component trees.
143
144
```javascript { .api }
145
/**
146
* Measures rendering performance of component tree
147
*/
148
const Profiler: ExoticComponent<ProfilerProps>;
149
150
interface ProfilerProps {
151
children?: ReactNode;
152
id: string;
153
onRender: ProfilerOnRenderCallback;
154
}
155
156
type ProfilerOnRenderCallback = (
157
id: string,
158
phase: "mount" | "update",
159
actualDuration: number,
160
baseDuration: number,
161
startTime: number,
162
commitTime: number,
163
interactions: Set<Interaction>
164
) => void;
165
```
166
167
**Usage Examples:**
168
169
```javascript
170
import React, { Profiler } from 'react';
171
172
function onRenderCallback(id, phase, actualDuration, baseDuration, startTime, commitTime) {
173
console.log('Profiler:', {
174
id, // "App" - the id prop of the Profiler tree that has just committed
175
phase, // "mount" (first render) or "update" (re-render)
176
actualDuration, // time spent rendering the committed update
177
baseDuration, // estimated time to render the entire subtree without memoization
178
startTime, // when React began rendering this update
179
commitTime // when React committed this update
180
});
181
182
// Send to analytics service
183
analytics.track('react_render', {
184
component: id,
185
phase,
186
duration: actualDuration,
187
timestamp: commitTime
188
});
189
}
190
191
function App() {
192
return (
193
<Profiler id="App" onRender={onRenderCallback}>
194
<Header />
195
<Profiler id="MainContent" onRender={onRenderCallback}>
196
<UserList />
197
<ProductGrid />
198
</Profiler>
199
<Footer />
200
</Profiler>
201
);
202
}
203
204
// Performance monitoring wrapper
205
function PerformanceWrapper({ id, children, threshold = 100 }) {
206
const handleRender = (id, phase, actualDuration) => {
207
if (actualDuration > threshold) {
208
console.warn(`Slow render detected in ${id}: ${actualDuration}ms`);
209
210
// Report slow renders
211
if (typeof reportWebVitals === 'function') {
212
reportWebVitals({
213
name: 'slow-render',
214
value: actualDuration,
215
id: id
216
});
217
}
218
}
219
};
220
221
return (
222
<Profiler id={id} onRender={handleRender}>
223
{children}
224
</Profiler>
225
);
226
}
227
228
// Usage
229
<PerformanceWrapper id="ExpensiveComponent" threshold={50}>
230
<ExpensiveDataVisualization />
231
</PerformanceWrapper>
232
```
233
234
### Suspense
235
236
Handles loading states for asynchronous components and data fetching.
237
238
```javascript { .api }
239
/**
240
* Handles loading states for async operations
241
*/
242
const Suspense: ExoticComponent<SuspenseProps>;
243
244
interface SuspenseProps {
245
children?: ReactNode;
246
fallback: NonNullable<ReactNode> | null;
247
}
248
```
249
250
**Usage Examples:**
251
252
```javascript
253
import React, { Suspense, lazy } from 'react';
254
255
// Lazy-loaded components
256
const LazyComponent = lazy(() => import('./LazyComponent'));
257
const UserProfile = lazy(() => import('./UserProfile'));
258
259
function App() {
260
return (
261
<div>
262
<h1>My App</h1>
263
<Suspense fallback={<div>Loading...</div>}>
264
<LazyComponent />
265
</Suspense>
266
</div>
267
);
268
}
269
270
// Nested suspense boundaries
271
function UserDashboard({ userId }) {
272
return (
273
<div>
274
<h2>Dashboard</h2>
275
<Suspense fallback={<SkeletonHeader />}>
276
<UserHeader userId={userId} />
277
<Suspense fallback={<SkeletonContent />}>
278
<UserContent userId={userId} />
279
</Suspense>
280
</Suspense>
281
</div>
282
);
283
}
284
285
// Data fetching with Suspense (requires data fetching library that supports Suspense)
286
function UserList() {
287
// This would throw a promise that Suspense catches
288
const users = useUsers(); // Suspense-compatible data fetching
289
290
return (
291
<ul>
292
{users.map(user => (
293
<li key={user.id}>{user.name}</li>
294
))}
295
</ul>
296
);
297
}
298
299
function App() {
300
return (
301
<Suspense fallback={<div>Loading users...</div>}>
302
<UserList />
303
</Suspense>
304
);
305
}
306
307
// Loading state component
308
function LoadingSpinner() {
309
return (
310
<div className="loading-spinner">
311
<div className="spinner"></div>
312
<p>Loading...</p>
313
</div>
314
);
315
}
316
317
// Route-based code splitting
318
function AppRouter() {
319
return (
320
<Router>
321
<Suspense fallback={<LoadingSpinner />}>
322
<Routes>
323
<Route path="/" element={<Home />} />
324
<Route path="/about" element={<LazyAbout />} />
325
<Route path="/profile" element={<LazyProfile />} />
326
</Routes>
327
</Suspense>
328
</Router>
329
);
330
}
331
```
332
333
### SuspenseList
334
335
Coordinates loading states of multiple Suspense components.
336
337
```javascript { .api }
338
/**
339
* Orchestrates loading order of multiple Suspense boundaries
340
*/
341
const SuspenseList: ExoticComponent<SuspenseListProps>;
342
343
interface SuspenseListProps {
344
children?: ReactNode;
345
revealOrder?: 'forwards' | 'backwards' | 'together';
346
tail?: 'collapsed' | 'hidden';
347
}
348
```
349
350
**Usage Examples:**
351
352
```javascript
353
import React, { Suspense, SuspenseList } from 'react';
354
355
// Control loading order
356
function ProfilePage() {
357
return (
358
<SuspenseList revealOrder="forwards">
359
<Suspense fallback={<ProfileSkeleton />}>
360
<ProfileHeader />
361
</Suspense>
362
<Suspense fallback={<ContentSkeleton />}>
363
<ProfileContent />
364
</Suspense>
365
<Suspense fallback={<SidebarSkeleton />}>
366
<ProfileSidebar />
367
</Suspense>
368
</SuspenseList>
369
);
370
}
371
372
// Load everything together
373
function Dashboard() {
374
return (
375
<SuspenseList revealOrder="together">
376
<Suspense fallback={<ChartSkeleton />}>
377
<SalesChart />
378
</Suspense>
379
<Suspense fallback={<TableSkeleton />}>
380
<DataTable />
381
</Suspense>
382
<Suspense fallback={<StatsSkeleton />}>
383
<StatsWidget />
384
</Suspense>
385
</SuspenseList>
386
);
387
}
388
389
// Control tail behavior
390
function PostList() {
391
return (
392
<SuspenseList revealOrder="forwards" tail="collapsed">
393
{posts.map(post => (
394
<Suspense key={post.id} fallback={<PostSkeleton />}>
395
<PostCard post={post} />
396
</Suspense>
397
))}
398
</SuspenseList>
399
);
400
}
401
402
// Nested SuspenseList
403
function AppLayout() {
404
return (
405
<div className="app-layout">
406
<header>
407
<Suspense fallback={<HeaderSkeleton />}>
408
<AppHeader />
409
</Suspense>
410
</header>
411
412
<main>
413
<SuspenseList revealOrder="together">
414
<Suspense fallback={<NavSkeleton />}>
415
<Navigation />
416
</Suspense>
417
418
<div className="content">
419
<SuspenseList revealOrder="forwards" tail="hidden">
420
<Suspense fallback={<ContentSkeleton />}>
421
<MainContent />
422
</Suspense>
423
<Suspense fallback={<SidebarSkeleton />}>
424
<Sidebar />
425
</Suspense>
426
</SuspenseList>
427
</div>
428
</SuspenseList>
429
</main>
430
</div>
431
);
432
}
433
```
434
435
## Types
436
437
```javascript { .api }
438
// Built-in component types
439
type ExoticComponent<P = {}> = (props: P) => ReactElement | null;
440
441
// Profiler callback types
442
interface Interaction {
443
id: number;
444
name: string;
445
timestamp: number;
446
}
447
448
// Suspense types
449
type SuspenseProps = {
450
children?: ReactNode;
451
fallback: NonNullable<ReactNode> | null;
452
};
453
454
type SuspenseListProps = {
455
children?: ReactNode;
456
revealOrder?: 'forwards' | 'backwards' | 'together';
457
tail?: 'collapsed' | 'hidden';
458
};
459
```