- Spec files
npm-react
Describes: pkg:npm/react@18.3.x
- Description
- React is a JavaScript library for building user interfaces with declarative, component-based architecture.
- Author
- tessl
- Last updated
builtin-components.md docs/
1# Built-in Components23React 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.45## Capabilities67### Fragment89Groups multiple elements without adding an extra DOM node.1011```javascript { .api }12/**13* Groups children without creating DOM wrapper14*/15const Fragment: ExoticComponent<{ children?: ReactNode }>;16```1718**Usage Examples:**1920```javascript21import React, { Fragment } from 'react';2223// Using Fragment component24function UserInfo({ user }) {25return (26<Fragment>27<h2>{user.name}</h2>28<p>{user.email}</p>29<p>{user.role}</p>30</Fragment>31);32}3334// Using short syntax35function UserInfo({ user }) {36return (37<>38<h2>{user.name}</h2>39<p>{user.email}</p>40<p>{user.role}</p>41</>42);43}4445// With key prop (useful in lists)46function ItemList({ items }) {47return (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}5859// Conditional fragments60function ConditionalContent({ showDetails, user }) {61return (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```7576### StrictMode7778Enables additional checks and warnings for development.7980```javascript { .api }81/**82* Enables additional development checks and warnings83*/84const StrictMode: ExoticComponent<{ children?: ReactNode }>;85```8687**Usage Examples:**8889```javascript90import React, { StrictMode } from 'react';9192// Wrap entire app in StrictMode93function App() {94return (95<StrictMode>96<Header />97<MainContent />98<Footer />99</StrictMode>100);101}102103// Wrap specific components for stricter checks104function DevelopmentApp() {105return (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}117118// StrictMode helps identify:119// - Components with unsafe lifecycles120// - Legacy string ref API usage121// - Deprecated findDOMNode usage122// - Unexpected side effects123// - Legacy context API124function ProblematicComponent() {125// StrictMode will warn about this deprecated lifecycle126UNSAFE_componentWillReceiveProps(nextProps) {127// This will trigger warnings in StrictMode128}129130// StrictMode will help detect side effects by double-invoking131useEffect(() => {132// This effect should be idempotent133console.log('Effect running'); // Will log twice in StrictMode134}, []);135136return <div>Component content</div>;137}138```139140### Profiler141142Measures performance of React component trees.143144```javascript { .api }145/**146* Measures rendering performance of component tree147*/148const Profiler: ExoticComponent<ProfilerProps>;149150interface ProfilerProps {151children?: ReactNode;152id: string;153onRender: ProfilerOnRenderCallback;154}155156type ProfilerOnRenderCallback = (157id: string,158phase: "mount" | "update",159actualDuration: number,160baseDuration: number,161startTime: number,162commitTime: number,163interactions: Set<Interaction>164) => void;165```166167**Usage Examples:**168169```javascript170import React, { Profiler } from 'react';171172function onRenderCallback(id, phase, actualDuration, baseDuration, startTime, commitTime) {173console.log('Profiler:', {174id, // "App" - the id prop of the Profiler tree that has just committed175phase, // "mount" (first render) or "update" (re-render)176actualDuration, // time spent rendering the committed update177baseDuration, // estimated time to render the entire subtree without memoization178startTime, // when React began rendering this update179commitTime // when React committed this update180});181182// Send to analytics service183analytics.track('react_render', {184component: id,185phase,186duration: actualDuration,187timestamp: commitTime188});189}190191function App() {192return (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}203204// Performance monitoring wrapper205function PerformanceWrapper({ id, children, threshold = 100 }) {206const handleRender = (id, phase, actualDuration) => {207if (actualDuration > threshold) {208console.warn(`Slow render detected in ${id}: ${actualDuration}ms`);209210// Report slow renders211if (typeof reportWebVitals === 'function') {212reportWebVitals({213name: 'slow-render',214value: actualDuration,215id: id216});217}218}219};220221return (222<Profiler id={id} onRender={handleRender}>223{children}224</Profiler>225);226}227228// Usage229<PerformanceWrapper id="ExpensiveComponent" threshold={50}>230<ExpensiveDataVisualization />231</PerformanceWrapper>232```233234### Suspense235236Handles loading states for asynchronous components and data fetching.237238```javascript { .api }239/**240* Handles loading states for async operations241*/242const Suspense: ExoticComponent<SuspenseProps>;243244interface SuspenseProps {245children?: ReactNode;246fallback: NonNullable<ReactNode> | null;247}248```249250**Usage Examples:**251252```javascript253import React, { Suspense, lazy } from 'react';254255// Lazy-loaded components256const LazyComponent = lazy(() => import('./LazyComponent'));257const UserProfile = lazy(() => import('./UserProfile'));258259function App() {260return (261<div>262<h1>My App</h1>263<Suspense fallback={<div>Loading...</div>}>264<LazyComponent />265</Suspense>266</div>267);268}269270// Nested suspense boundaries271function UserDashboard({ userId }) {272return (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}284285// Data fetching with Suspense (requires data fetching library that supports Suspense)286function UserList() {287// This would throw a promise that Suspense catches288const users = useUsers(); // Suspense-compatible data fetching289290return (291<ul>292{users.map(user => (293<li key={user.id}>{user.name}</li>294))}295</ul>296);297}298299function App() {300return (301<Suspense fallback={<div>Loading users...</div>}>302<UserList />303</Suspense>304);305}306307// Loading state component308function LoadingSpinner() {309return (310<div className="loading-spinner">311<div className="spinner"></div>312<p>Loading...</p>313</div>314);315}316317// Route-based code splitting318function AppRouter() {319return (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```332333### SuspenseList334335Coordinates loading states of multiple Suspense components.336337```javascript { .api }338/**339* Orchestrates loading order of multiple Suspense boundaries340*/341const SuspenseList: ExoticComponent<SuspenseListProps>;342343interface SuspenseListProps {344children?: ReactNode;345revealOrder?: 'forwards' | 'backwards' | 'together';346tail?: 'collapsed' | 'hidden';347}348```349350**Usage Examples:**351352```javascript353import React, { Suspense, SuspenseList } from 'react';354355// Control loading order356function ProfilePage() {357return (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}371372// Load everything together373function Dashboard() {374return (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}388389// Control tail behavior390function PostList() {391return (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}401402// Nested SuspenseList403function AppLayout() {404return (405<div className="app-layout">406<header>407<Suspense fallback={<HeaderSkeleton />}>408<AppHeader />409</Suspense>410</header>411412<main>413<SuspenseList revealOrder="together">414<Suspense fallback={<NavSkeleton />}>415<Navigation />416</Suspense>417418<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```434435## Types436437```javascript { .api }438// Built-in component types439type ExoticComponent<P = {}> = (props: P) => ReactElement | null;440441// Profiler callback types442interface Interaction {443id: number;444name: string;445timestamp: number;446}447448// Suspense types449type SuspenseProps = {450children?: ReactNode;451fallback: NonNullable<ReactNode> | null;452};453454type SuspenseListProps = {455children?: ReactNode;456revealOrder?: 'forwards' | 'backwards' | 'together';457tail?: 'collapsed' | 'hidden';458};459```