### Complete React app example with HTML, index.js, and App.js Source: https://react.dev/reference/react-dom/client/createRoot Full working example showing the HTML entry point with a root div, the index.js file that initializes React, and the App.js component with a simple counter. The index.js file is marked as active in the interactive example. ```html My app
``` ```javascript import { createRoot } from 'react-dom/client'; import App from './App.js'; import './styles.css'; const root = createRoot(document.getElementById('root')); root.render(); ``` ```javascript import { useState } from 'react'; export default function App() { return ( <>

Hello, world!

); } function Counter() { const [count, setCount] = useState(0); return ( ); } ``` -------------------------------- ### Complete Context Consumption Example Source: https://react.dev/learn/passing-data-deeply-with-context A full multi-file example demonstrating context consumption, including the component logic, context definition, and styling. ```js import Heading from './Heading.js'; import Section from './Section.js'; export default function Page() { return (
Title
Heading Heading Heading
Sub-heading Sub-heading Sub-heading
Sub-sub-heading Sub-sub-heading Sub-sub-heading
); } ``` ```js export default function Section({ children }) { return (
{children}
); } ``` ```js import { useContext } from 'react'; import { LevelContext } from './LevelContext.js'; export default function Heading({ children }) { const level = useContext(LevelContext); switch (level) { case 1: return

{children}

; case 2: return

{children}

; case 3: return

{children}

; case 4: return

{children}

; case 5: return
{children}
; case 6: return
{children}
; default: throw Error('Unknown level: ' + level); } } ``` ```js import { createContext } from 'react'; export const LevelContext = createContext(1); ``` ```css .section { padding: 10px; margin: 5px; border-radius: 5px; border: 1px solid #aaa; } ``` -------------------------------- ### React App with Activity and ViewTransition for Pre-rendering Details Source: https://react.dev/blog/2025/04/23/react-labs-view-transitions-activity-and-more This example showcases a complete React application integrating for pre-rendering and for animated UI changes. App.js manages the overall layout and uses to pre-render video detail pages. Details.js handles the display of individual video information, incorporating Suspense and ViewTransition for smooth loading. Home.js provides the main video listing. This setup ensures a seamless user experience by having content ready before navigation. ```js import { Activity, ViewTransition, use } from "react"; import Details from "./Details"; import Home from "./Home"; import { useRouter } from "./router"; import {fetchVideos} from './data'; export default function App() { const { url } = useRouter(); const videoId = url.split("/").pop(); const videos = use(fetchVideos()); return ( {/* Render videos in Activity to pre-render them */} {videos.map(({id}) => (
))} ); } ``` ```js import { use, Suspense, ViewTransition } from "react"; import { fetchVideo, fetchVideoDetails } from "./data"; import { Thumbnail, VideoControls } from "./Videos"; import { useRouter } from "./router"; import Layout from "./Layout"; import { ChevronLeft } from "./Icons"; function VideoDetails({id}) { // Animate from Suspense fallback to content. // If this is pre-rendered then the fallback // won't need to show. return ( } > {/* Animate the content up */} ); } function VideoInfoFallback() { return ( <>
); } export default function Details({id}) { const { url, navigateBack } = useRouter(); const video = use(fetchVideo(id)); return ( { navigateBack("/"); }} > Back } >
); } function VideoInfo({ id }) { const details = use(fetchVideoDetails(id)); return ( <>

{details.title}

{details.description}

); } ``` ```js import { useId, useState, use, useDeferredValue, ViewTransition } from "react";import { Video } from "./Videos";import Layout from "./Layout";import { fetchVideos } from "./data";import { IconSearch } from "./Icons"; function SearchList({searchText, videos}) { // Activate with useDeferredValue ("when") const deferredSearchText = useDeferredValue(searchText); const filteredVideos = filterVideos(videos, deferredSearchText); return (
{filteredVideos.length === 0 && (
No results
)}
{filteredVideos.map((video) => ( // Animate each item in list ("what") ))}
); } export default function Home() { const videos = use(fetchVideos()); const count = videos.length; const [searchText, setSearchText] = useState(''); return ( {count} Videos}> ); } function SearchInput({ value, onChange }) { const id = useId(); return ( ``` -------------------------------- ### Complete Example: `useList` Hook in a React Application Source: https://react.dev/reference/react/cloneElement Full implementation of a React application demonstrating the `useList` custom Hook, including component definitions, data, and styling. This setup allows for interactive testing of the custom Hook's functionality. ```js import Row from './Row.js'; import useList from './useList.js'; import { products } from './data.js'; export default function App() { const [selected, onNext] = useList(products); return (
{products.map(product => )}
); } ``` ```js import { useState } from 'react'; export default function useList(items) { const [selectedIndex, setSelectedIndex] = useState(0); function onNext() { setSelectedIndex(i => (i + 1) % items.length ); } const selected = items[selectedIndex]; return [selected, onNext]; } ``` ```js export default function Row({ title, isHighlighted }) { return (
{title}
); } ``` ```js export const products = [ { title: 'Cabbage', id: 1 }, { title: 'Garlic', id: 2 }, { title: 'Apple', id: 3 } ]; ``` ```css .List { display: flex; flex-direction: column; border: 2px solid grey; padding: 5px; } .Row { border: 2px dashed black; padding: 5px; margin: 5px; } .RowHighlighted { background: #ffa; } button { height: 40px; font-size: 20px; } ``` -------------------------------- ### Complete Hydration Example with Server-Rendered HTML Source: https://react.dev/reference/react-dom/client/hydrateRoot Full example demonstrating server-rendered HTML hydration with a React component. Includes HTML markup generated by react-dom/server and a client-side React component with state management. Shows the complete setup for converting static server HTML into an interactive application. ```HTML

Hello, world!

``` ```JavaScript import './styles.css'; import { hydrateRoot } from 'react-dom/client'; import App from './App.js'; hydrateRoot( document.getElementById('root'), ); ``` ```JavaScript import { useState } from 'react'; export default function App() { return ( <>

Hello, world!

); } function Counter() { const [count, setCount] = useState(0); return ( ); } ``` -------------------------------- ### Install React Compiler Beta with npm Source: https://react.dev/blog/2024/10/21/react-compiler-beta-release Install the React Compiler Beta and ESLint plugin using npm package manager. This command installs both babel-plugin-react-compiler and eslint-plugin-react-compiler from the beta tag on npm registry. ```bash npm install -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta ``` -------------------------------- ### Cleanup Logic Without Setup (Anti-pattern) Source: https://react.dev/reference/react/useEffect Example of cleanup code without corresponding setup logic, which is a code smell and should be avoided. Cleanup should be symmetrical to setup. ```javascript useEffect(() => { // πŸ”΄ Avoid: Cleanup logic without corresponding setup logic return () => { doSomething(); }; }, []); ``` -------------------------------- ### React Component Rendering Example Source: https://react.dev/learn/render-and-commit Illustrates how React recursively calls components like Gallery and Image during the rendering phase to build the UI. This setup demonstrates an initial render of multiple nested components. ```javascript export default function Gallery() { return (

Inspiring Sculptures

); } function Image() { return ( 'Floralis GenΓ©rica' by Eduardo Catalano: a gigantic metallic flower sculpture with reflective petals ); } ``` ```javascript import Gallery from './Gallery.js'; import { createRoot } from 'react-dom/client'; const root = createRoot(document.getElementById('root')) root.render(); ``` ```css img { margin: 0 10px 10px 0; } ``` -------------------------------- ### Complete App with Render Prop Example Source: https://react.dev/reference/react/cloneElement A full working example showing App component using List with a renderItem prop to render products as Row components with highlight state. ```javascript import List from './List.js'; import Row from './Row.js'; import { products } from './data.js'; export default function App() { return ( } /> ); } ``` -------------------------------- ### Install React Compiler Beta with Yarn Source: https://react.dev/blog/2024/10/21/react-compiler-beta-release Install the React Compiler Beta and ESLint plugin using Yarn package manager. This is an alternative to npm for installing both the compiler and linter packages from the beta release. ```bash yarn add -D babel-plugin-react-compiler@beta eslint-plugin-react-compiler@beta ``` -------------------------------- ### Basic Gating Configuration for JavaScript Compiler Source: https://react.dev/reference/react-compiler/gating This snippet demonstrates the fundamental configuration for the `gating` option within a JavaScript compiler setup. It illustrates how to specify a placeholder `source` module path and the `importSpecifierName` of the exported function that will serve as the runtime feature flag. This initial setup guides the compiler on where to find the conditional logic. ```js { gating: { source: 'my-feature-flags', importSpecifierName: 'shouldUseCompiler' } } ``` -------------------------------- ### Complete Application Example with Context Source: https://react.dev/reference/react/cloneElement This Sandpack example demonstrates a full React application using context for highlighting list items. It includes the `App`, `List`, `Row`, and `HighlightContext` components, along with sample data and CSS. ```javascript import List from './List.js'; import Row from './Row.js'; import { products } from './data.js'; export default function App() { return ( } /> ); } ``` ```javascript import { useState } from 'react'; import { HighlightContext } from './HighlightContext.js'; export default function List({ items, renderItem }) { const [selectedIndex, setSelectedIndex] = useState(0); return (
{items.map((item, index) => { const isHighlighted = index === selectedIndex; return ( {renderItem(item)} ); })}
); } ``` ```javascript import { useContext } from 'react'; import { HighlightContext } from './HighlightContext.js'; export default function Row({ title }) { const isHighlighted = useContext(HighlightContext); return (
{title}
); } ``` ```javascript import { createContext } from 'react'; export const HighlightContext = createContext(false); ``` ```javascript export const products = [ { title: 'Cabbage', id: 1 }, { title: 'Garlic', id: 2 }, { title: 'Apple', id: 3 }, ]; ``` ```css .List { display: flex; flex-direction: column; border: 2px solid grey; padding: 5px; } .Row { border: 2px dashed black; padding: 5px; margin: 5px; } .RowHighlighted { background: #ffa; } button { height: 40px; font-size: 20px; } ``` -------------------------------- ### Styling for Initial Form Example Source: https://react.dev/learn/state-a-components-memory This CSS provides basic styling for the form's heading element in the initial example. ```css h1 { margin-top: 10px; } ``` -------------------------------- ### Complete `createElement` example with styling Source: https://react.dev/reference/react/createElement This comprehensive example demonstrates a full React application using `createElement` for both HTML elements and custom components. It includes the `Greeting` component definition and its rendering in the `App` component, along with associated CSS for styling the greeting. ```js import { createElement } from 'react'; function Greeting({ name }) { return createElement( 'h1', { className: 'greeting' }, 'Hello ', createElement('i', null, name), '. Welcome!' ); } export default function App() { return createElement( Greeting, { name: 'Taylor' } ); } ``` ```css .greeting { color: darkgreen; font-family: Georgia; } ``` -------------------------------- ### Initial Effect setup with empty dependencies Source: https://react.dev/learn/removing-effect-dependencies Shows the initial `useEffect` setup for a chat connection. The empty dependency array will trigger linter warnings for missing reactive values. ```javascript const serverUrl = 'https://localhost:1234'; function ChatRoom({ roomId }) { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => connection.disconnect(); // ... } ``` -------------------------------- ### Complete JSX example with styling Source: https://react.dev/reference/react/createElement This full example showcases a React application built entirely with JSX, demonstrating the `Greeting` component and its usage within the `App` component. It provides a direct comparison to the `createElement` approach, including the same CSS styling. ```js function Greeting({ name }) { return (

Hello {name}. Welcome!

); } export default function App() { return ; } ``` ```css .greeting { color: darkgreen; font-family: Georgia; } ``` -------------------------------- ### Symmetrical Setup and Cleanup with useEffect Source: https://react.dev/reference/react/useEffect Proper pattern showing symmetrical setup and cleanup logic. The cleanup function disconnects the connection that was established in setup, demonstrating the correct relationship between setup and cleanup. ```javascript useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => { connection.disconnect(); }; }, [serverUrl, roomId]); ``` -------------------------------- ### Complete shared counter example with styles Source: https://react.dev/learn Full working example demonstrating lifted state with two buttons that share and update the same count together. Includes CSS styling for button layout. ```javascript import { useState } from 'react'; export default function MyApp() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return (

Counters that update together

); } function MyButton({ count, onClick }) { return ( ); } ``` ```css button { display: block; margin-bottom: 5px; } ``` -------------------------------- ### Basic preloadModule usage Source: https://react.dev/reference/react-dom/preloadModule Simple example showing how to preload an ESM module with the required 'as' option. ```javascript preloadModule("https://example.com/module.js", {as: "script"}); ``` -------------------------------- ### Example of state preservation with Activity Source: https://react.dev/reference/react/Activity A complete example showing how the Activity boundary preserves the sidebar's internal state even when hidden. ```javascript import { Activity, useState } from 'react'; import Sidebar from './Sidebar.js'; export default function App() { const [isShowingSidebar, setIsShowingSidebar] = useState(true); return ( <>

Main content

); } ``` ```javascript import { useState } from 'react'; export default function Sidebar() { const [isExpanded, setIsExpanded] = useState(false) return ( ); } ``` ```css body { height: 275px; margin: 0; } #root { display: flex; gap: 10px; height: 100%; } nav { padding: 10px; background: #eee; font-size: 14px; height: 100%; } main { padding: 10px; } p { margin: 0; } h1 { margin-top: 10px; } .indicator { margin-left: 4px; display: inline-block; rotate: 90deg; } .indicator.down { rotate: 180deg; } ``` -------------------------------- ### Install React Compiler Babel Plugin Source: https://react.dev/blog/2025/10/07/react-compiler-1 Instructions for installing the 'babel-plugin-react-compiler' as a development dependency using different package managers: npm, pnpm, and yarn. ```npm npm install --save-dev --save-exact babel-plugin-react-compiler@latest ``` ```pnpm pnpm add --save-dev --save-exact babel-plugin-react-compiler@latest ``` ```yarn yarn add --dev --exact babel-plugin-react-compiler@latest ``` -------------------------------- ### Troubleshooting: Component Not Compiled in Infer Mode Source: https://react.dev/reference/react-compiler/compilationMode Troubleshooting guide for components not being compiled in 'infer' mode, with examples of correct naming conventions and hook usage patterns. ```APIDOC ## Troubleshooting: Component Not Compiled in Infer Mode ### Description In `'infer'` mode, ensure your component follows React conventions to be compiled. ### Common Issues and Solutions #### Issue 1: Lowercase component name ```js // ❌ Won't be compiled: lowercase name function button(props) { return ; } // βœ… Will be compiled: PascalCase name function Button(props) { return ; } ``` #### Issue 2: Hook without hook calls ```js // ❌ Won't be compiled: doesn't create JSX or call hooks function useData() { return window.localStorage.getItem('data'); } // βœ… Will be compiled: calls a hook function useData() { const [data] = useState(() => window.localStorage.getItem('data')); return data; } ``` ### Requirements for Infer Mode Compilation - Component functions must use PascalCase naming - Hook functions must start with `use` prefix - Functions must either create JSX or call other React hooks - Functions must be named according to React conventions ``` -------------------------------- ### Full example: Integrating a custom external store with useSyncExternalStore Source: https://react.dev/reference/react/useSyncExternalStore This example shows a complete integration of a custom external `todosStore` with a React component using `useSyncExternalStore`. It includes both the React component and the external store's implementation. ```js import { useSyncExternalStore } from 'react'; import { todosStore } from './todoStore.js'; export default function TodosApp() { const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot); return ( <>
    {todos.map(todo => (
  • {todo.text}
  • ))}
); } ``` ```js // This is an example of a third-party store // that you might need to integrate with React. // If your app is fully built with React, // we recommend using React state instead. let nextId = 0; let todos = [{ id: nextId++, text: 'Todo #1' }]; let listeners = []; export const todosStore = { addTodo() { todos = [...todos, { id: nextId++, text: 'Todo #' + nextId }] emitChange(); }, subscribe(listener) { listeners = [...listeners, listener]; return () => { listeners = listeners.filter(l => l !== listener); }; }, getSnapshot() { return todos; } }; function emitChange() { for (let listener of listeners) { listener(); } } ``` -------------------------------- ### Chat Room Synchronization and Cleanup Example Source: https://react.dev/learn/lifecycle-of-reactive-effects A complete example showing a ChatRoom component that connects to a server. React will trigger the connection/disconnection cycle twice on mount in development to verify logic. ```javascript import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; const serverUrl = 'https://localhost:1234'; function ChatRoom({ roomId }) { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => connection.disconnect(); }, [roomId]); return

Welcome to the {roomId} room!

; } export default function App() { const [roomId, setRoomId] = useState('general'); const [show, setShow] = useState(false); return ( <> {show &&
} {show && } ); } ``` ```javascript export function createConnection(serverUrl, roomId) { // A real implementation would actually connect to the server return { connect() { console.log('βœ… Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; } ``` ```css input { display: block; margin-bottom: 20px; } button { margin-left: 10px; } ``` -------------------------------- ### Animation example CSS styling Source: https://react.dev/reference/react/useEffect Basic CSS for layout and sizing of the animation example component. ```CSS label, button { display: block; margin-bottom: 20px; } html, body { min-height: 300px; } ``` -------------------------------- ### Install React Dependencies Source: https://react.dev/learn/add-react-to-an-existing-project Uses npm to install the react and react-dom packages, which are necessary for building and rendering React components. ```bash npm install react react-dom ``` -------------------------------- ### Counter Component Example Source: https://react.dev/reference/react/act Sample component with state and effects used in test examples. Demonstrates a simple counter that updates document title on click. ```javascript function Counter() { const [count, setCount] = useState(0); const handleClick = () => { setCount(prev => prev + 1); } useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return (

You clicked {count} times

) } ``` -------------------------------- ### Implement a comprehensive React error reporting system Source: https://react.dev/reference/react-dom/client/createRoot This example shows how to set up a complete error reporting system using `onCaughtError`, `onUncaughtError`, and `onRecoverableError` with `createRoot`. It includes a utility for reporting errors and an example App component to trigger different error types. ```js function reportError({ type, error, errorInfo }) { // The specific implementation is up to you. // `console.error()` is only used for demonstration purposes. console.error(type, error, "Component Stack: "); console.error("Component Stack: ", errorInfo.componentStack); } export function onCaughtErrorProd(error, errorInfo) { if (error.message !== "Known error") { reportError({ type: "Caught", error, errorInfo }); } } export function onUncaughtErrorProd(error, errorInfo) { reportError({ type: "Uncaught", error, errorInfo }); } export function onRecoverableErrorProd(error, errorInfo) { reportError({ type: "Recoverable", error, errorInfo }); } ``` ```js import { createRoot } from "react-dom/client"; import App from "./App.js"; import { onCaughtErrorProd, onRecoverableErrorProd, onUncaughtErrorProd, } from "./reportError"; const container = document.getElementById("root"); const root = createRoot(container, { // Keep in mind to remove these options in development to leverage // React's default handlers or implement your own overlay for development. // The handlers are only specfied unconditionally here for demonstration purposes. onCaughtError: onCaughtErrorProd, onRecoverableError: onRecoverableErrorProd, onUncaughtError: onUncaughtErrorProd, }); root.render(); ``` ```js import { Component, useState } from "react"; function Boom() { foo.bar = "baz"; } class ErrorBoundary extends Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } render() { if (this.state.hasError) { return

Something went wrong.

; } return this.props.children; } } export default function App() { const [triggerUncaughtError, settriggerUncaughtError] = useState(false); const [triggerCaughtError, setTriggerCaughtError] = useState(false); return ( <> {triggerUncaughtError && } {triggerCaughtError && ( )} ); } ``` -------------------------------- ### Complete ViewTransition Example with Type-Based Animation Source: https://react.dev/reference/react/ViewTransition Full working example showing ViewTransition with both onEnter and onExit handlers that respond to transition types, integrated with addTransitionType to mark transitions as 'fast' and control animation durations. ```javascript import {ViewTransition, useState, startTransition, addTransitionType} from 'react'; import {Video} from './Video'; import videos from './data'; import {SLIDE_IN, SLIDE_OUT} from './animations'; function Item() { return ( { const duration = types.includes('fast') ? 150 : 2000; const anim = instance.new.animate( SLIDE_IN, {duration: duration, easing: 'ease-out'} ); return () => anim.cancel(); }} onExit={(instance, types) => { const duration = types.includes('fast') ? 150 : 500; const anim = instance.old.animate( SLIDE_OUT, {duration: duration, easing: 'ease-in'} ); return () => anim.cancel(); }}> ); } export default function Component() { const [showItem, setShowItem] = useState(false); const [isFast, setIsFast] = useState(false); return ( <>
Fast: {setIsFast(f => !f)}} value={isFast}>

{showItem ? : null} ); } ``` -------------------------------- ### Preconnecting in an event handler Source: https://react.dev/reference/react-dom/preconnect Use preconnect in event handlers to start the connection process before a state transition or navigation occurs. This gets the process started earlier than if you call it during the rendering of the new page. ```javascript import { preconnect } from 'react-dom'; function CallToAction() { const onClick = () => { preconnect('http://example.com'); startWizard(); } return ( ); } ``` -------------------------------- ### Render a basic list of items Source: https://react.dev/learn/conditional-rendering A starting point showing a list of items without any conditional logic applied to the props. ```js function Item({ name, isPacked }) { return
  • {name}
  • ; } export default function PackingList() { return (

    Sally Ride's Packing List

    ); } ``` -------------------------------- ### Complete chat room example with empty dependency array Source: https://react.dev/learn/lifecycle-of-reactive-effects Demonstrates a chat connection that synchronizes only on mount and unmount because its dependencies are static. Includes the component logic, connection helper, and basic styling. ```javascript import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; const serverUrl = 'https://localhost:1234'; const roomId = 'general'; function ChatRoom() { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => connection.disconnect(); }, []); return

    Welcome to the {roomId} room!

    ; } export default function App() { const [show, setShow] = useState(false); return ( <> {show &&
    } {show && } ); } ``` ```javascript export function createConnection(serverUrl, roomId) { // A real implementation would actually connect to the server return { connect() { console.log('βœ… Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; } ``` ```css input { display: block; margin-bottom: 20px; } button { margin-left: 10px; } ``` -------------------------------- ### Complete Example of `use` Hook with Context and Styling Source: https://react.dev/reference/react/use This comprehensive example demonstrates the `use` Hook for context consumption across multiple nested components, including conditional usage, along with associated CSS styling. ```js import { createContext, use } from 'react'; const ThemeContext = createContext(null); export default function MyApp() { return (
    ) } function Form() { return ( ); } function Panel({ title, children }) { const theme = use(ThemeContext); const className = 'panel-' + theme; return (

    {title}

    {children}
    ) } function Button({ show, children }) { if (show) { const theme = use(ThemeContext); const className = 'button-' + theme; return ( ); } return false } ``` ```css .panel-light, .panel-dark { border: 1px solid black; border-radius: 4px; padding: 20px; } .panel-light { color: #222; background: #fff; } .panel-dark { color: #fff; background: rgb(23, 32, 42); } .button-light, .button-dark { border: 1px solid #777; padding: 5px; margin-right: 10px; margin-top: 10px; } .button-dark { background: #222; color: #fff; } .button-light { background: #fff; color: #222; } ``` -------------------------------- ### Sample Data for Render Prop Example Source: https://react.dev/reference/react/cloneElement Product data array used in the render prop example, containing objects with title and id properties. ```javascript export const products = [ { title: 'Cabbage', id: 1 }, { title: 'Garlic', id: 2 }, { title: 'Apple', id: 3 }, ]; ``` -------------------------------- ### Eagerly fetch and evaluate a stylesheet or external script Source: https://react.dev/reference/react-dom/preinit Use preinit to hint to the browser to start downloading and executing a resource. Scripts are executed upon download completion, and stylesheets are inserted immediately. ```javascript preinit("https://example.com/script.js", {as: "script"}); ``` -------------------------------- ### Complete Gallery Component Example Source: https://react.dev/learn/state-a-components-memory A full implementation of a gallery component using state to navigate through a list of sculptures. ```js import { useState } from 'react'; import { sculptureList } from './data.js'; export default function Gallery() { const [index, setIndex] = useState(0); function handleClick() { setIndex(index + 1); } let sculpture = sculptureList[index]; return ( <>

    {sculpture.name} by {sculpture.artist}

    ({index + 1} of {sculptureList.length})

    {sculpture.alt}

    {sculpture.description}

    ); } ``` -------------------------------- ### Full example: Integrate React Portal with a Leaflet map widget popup Source: https://react.dev/reference/react-dom/createPortal This comprehensive example showcases the integration of React Portals with a third-party Leaflet map widget. It demonstrates how to initialize the map, create a popup, and then render a React component directly into that popup's DOM node using createPortal, providing a complete, runnable solution for external DOM node integration. ```json { "dependencies": { "leaflet": "1.9.1", "react": "latest", "react-dom": "latest", "react-scripts": "latest", "remarkable": "2.0.1" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } } ``` ```javascript import { useRef, useEffect, useState } from 'react'; import { createPortal } from 'react-dom'; import { createMapWidget, addPopupToMapWidget } from './map-widget.js'; export default function Map() { const containerRef = useRef(null); const mapRef = useRef(null); const [popupContainer, setPopupContainer] = useState(null); useEffect(() => { if (mapRef.current === null) { const map = createMapWidget(containerRef.current); mapRef.current = map; const popupDiv = addPopupToMapWidget(map); setPopupContainer(popupDiv); } }, []); return (
    {popupContainer !== null && createPortal(

    Hello from React!

    , popupContainer )}
    ); } ``` ```javascript import 'leaflet/dist/leaflet.css'; import * as L from 'leaflet'; export function createMapWidget(containerDomNode) { const map = L.map(containerDomNode); map.setView([0, 0], 0); L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: 'Β© OpenStreetMap' }).addTo(map); return map; } export function addPopupToMapWidget(map) { const popupDiv = document.createElement('div'); L.popup() .setLatLng([0, 0]) .setContent(popupDiv) .openOn(map); return popupDiv; } ``` ```css button { margin: 5px; } ``` -------------------------------- ### Blog component rendering list of fragments Source: https://react.dev/reference/react/Fragment Complete example demonstrating how to render multiple fragments in a loop with proper `key` props and no wrapper DOM elements. ```jsx import { Fragment } from 'react'; const posts = [ { id: 1, title: 'An update', body: "It's been a while since I posted..." }, { id: 2, title: 'My new blog', body: 'I am starting a new blog!' } ]; export default function Blog() { return posts.map(post => ); } function PostTitle({ title }) { return

    {title}

    } function PostBody({ body }) { return (

    {body}

    ); } ``` -------------------------------- ### Complete Lazy-loading Example with React Suspense Source: https://react.dev/reference/react/lazy A comprehensive example demonstrating lazy-loading a `MarkdownPreview` component using `lazy` and `Suspense` within a React application. Includes a simulated delay for demonstration purposes and supporting files. ```javascript import { useState, Suspense, lazy } from 'react'; import Loading from './Loading.js'; const MarkdownPreview = lazy(() => delayForDemo(import('./MarkdownPreview.js'))); export default function MarkdownEditor() { const [showPreview, setShowPreview] = useState(false); const [markdown, setMarkdown] = useState('Hello, **world**!'); return ( <>

    That's right!

    ``` -------------------------------- ### Initialize useReducer with initial state directly Source: https://react.dev/reference/react/useReducer This example initializes the state directly without an initializer function. The createInitialState function runs on every render, which is less efficient. ```javascript import TodoList from './TodoList.js'; export default function App() { return ; } ``` ```javascript import { useReducer } from 'react'; function createInitialState(username) { const initialTodos = []; for (let i = 0; i < 50; i++) { initialTodos.push({ id: i, text: username + "'s task #" + (i + 1) }); } return { draft: '', todos: initialTodos, }; } function reducer(state, action) { switch (action.type) { case 'changed_draft': { return { draft: action.nextDraft, todos: state.todos, }; }; case 'added_todo': { return { draft: '', todos: [{ id: state.todos.length, text: state.draft }, ...state.todos] } } } throw Error('Unknown action: ' + action.type); } export default function TodoList({ username }) { const [state, dispatch] = useReducer( reducer, createInitialState(username) ); return ( <> { dispatch({ type: 'changed_draft', nextDraft: e.target.value }) }} />
      {state.todos.map(item => (
    • {item.text}
    • ))}
    ); } ``` -------------------------------- ### Configure React Compiler in Vite with @vitejs/plugin-react Source: https://react.dev/learn/react-compiler/installation Example vite.config.js demonstrating how to integrate babel-plugin-react-compiler via the babel option of @vitejs/plugin-react. This method is suitable when using Vite's official React plugin. ```javascript // vite.config.js import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [ react({ babel: { plugins: ['babel-plugin-react-compiler'], }, }), ], }); ``` -------------------------------- ### Install React 18 RC via npm Source: https://react.dev/blog/2021/12/17/react-conf-2021-recap Install React 18 Release Candidate and React DOM RC packages using npm. This command upgrades the React library to the RC version that will become the stable release in early 2022. ```bash npm install react@rc react-dom@rc ``` -------------------------------- ### renderToPipeableStream with bootstrapScripts and onShellReady Source: https://react.dev/reference/react-dom/server/renderToPipeableStream Complete example rendering a React App component with bootstrap scripts and streaming to an HTTP response when the shell is ready. Requires client-side hydrateRoot call to make the HTML interactive. ```javascript import { renderToPipeableStream } from 'react-dom/server'; const { pipe } = renderToPipeableStream(, { bootstrapScripts: ['/main.js'], onShellReady() { response.setHeader('content-type', 'text/html'); pipe(response); } }); ``` -------------------------------- ### Managing Chat Room Connection with useEffect Dependencies Source: https://react.dev/learn/escape-hatches This example demonstrates how `useEffect` re-synchronizes an external connection when a reactive dependency (`roomId`) changes. It includes the main React component, a utility for creating connections, and basic styling. ```javascript import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; const serverUrl = 'https://localhost:1234'; function ChatRoom({ roomId }) { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => connection.disconnect(); }, [roomId]); return

    Welcome to the {roomId} room!

    ; } export default function App() { const [roomId, setRoomId] = useState('general'); return ( <>
    ); } ``` ```javascript export function createConnection(serverUrl, roomId) { // A real implementation would actually connect to the server return { connect() { console.log('βœ… Connecting to "' + roomId + '" room at ' + serverUrl + '...'); }, disconnect() { console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); } }; } ``` ```css input { display: block; margin-bottom: 20px; } button { margin-left: 10px; } ``` -------------------------------- ### Resuming a Prerendered React Tree in Node.js Source: https://react.dev/reference/react-dom/static/resumeAndPrerenderToNodeStream Demonstrates how to import and use resumeAndPrerenderToNodeStream within an asynchronous handler to pipe the HTML prelude to a writable stream. This example shows retrieving the postponed state from storage and parsing it before resuming the render. ```javascript import { resumeAndPrerenderToNodeStream } from 'react-dom/static'; import { getPostponedState } from 'storage'; async function handler(request, writable) { const postponedState = getPostponedState(request); const { prelude } = await resumeAndPrerenderToNodeStream(, JSON.parse(postponedState)); prelude.pipe(writable); } ``` -------------------------------- ### Complete Chat Room Implementation with Custom Hook Source: https://react.dev/learn/reusing-logic-with-custom-hooks A full example showing the interaction between a parent App component, a ChatRoom UI component, and the optimized useChatRoom Hook. It includes state management for room selection and server configuration. ```javascript import { useState } from 'react'; import { useChatRoom } from './useChatRoom.js'; import { showNotification } from './notifications.js'; export default function ChatRoom({ roomId }) { const [serverUrl, setServerUrl] = useState('https://localhost:1234'); useChatRoom({ roomId: roomId, serverUrl: serverUrl, onReceiveMessage(msg) { showNotification('New message: ' + msg); } }); return ( <>

    Welcome to the {roomId} room!

    ); } ``` -------------------------------- ### Basic Tabbed Interface with Unmounting Source: https://react.dev/reference/react/Activity This example shows a basic tabbed interface where inactive components are unmounted. This is the default behavior for managing component visibility and their associated side effects. ```javascript import { useState } from 'react'; import TabButton from './TabButton.js'; import Home from './Home.js'; import Video from './Video.js'; export default function App() { const [activeTab, setActiveTab] = useState('video'); return ( <> setActiveTab('home')} > Home setActiveTab('video')} > Video
    {activeTab === 'home' && } {activeTab === 'video' &&