### 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 ``` -------------------------------- ### 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]); ``` -------------------------------- ### 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 ``` -------------------------------- ### 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; } ``` -------------------------------- ### 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 ( ); } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 `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; } ``` -------------------------------- ### 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; } ``` -------------------------------- ### Initialize a React project with Rsbuild Source: https://react.dev/learn/build-a-react-app-from-scratch Use the Rsbuild CLI to create a new React application with pre-configured performance optimizations. ```bash npx create-rsbuild --template react ``` -------------------------------- ### Rendering Multiple Counters from a Single JSX Variable Source: https://react.dev/learn/preserving-and-resetting-state This example shows that even when a component is rendered multiple times using the same JSX variable, each instance gets its own isolated state because they occupy different positions in the render tree. ```javascript import { useState } from 'react'; export default function App() { const counter = ; return (
{counter} {counter}
); } function Counter() { const [score, setScore] = useState(0); const [hover, setHover] = useState(false); let className = 'counter'; if (hover) { className += ' hover'; } return (
setHover(true)} onPointerLeave={() => setHover(false)} >

{score}

); } ``` ```css label { display: block; clear: both; } .counter { width: 100px; text-align: center; border: 1px solid gray; border-radius: 4px; padding: 20px; margin: 0 20px 20px 0; float: left; } .hover { background: #ffffd8; } ``` -------------------------------- ### Identify Non-Reactive Bug in React Timer Source: https://react.dev/learn/separating-events-from-effects This example demonstrates a common bug where wrapping interval setup in a useEffectEvent (onMount) prevents the timer from reacting to changes in the delay state. The interval is created once and never updated because the Effect has no dependencies. ```javascript import { useState, useEffect } from 'react'; import { useEffectEvent } from 'react'; export default function Timer() { const [count, setCount] = useState(0); const [increment, setIncrement] = useState(1); const [delay, setDelay] = useState(100); const onTick = useEffectEvent(() => { setCount(c => c + increment); }); const onMount = useEffectEvent(() => { return setInterval(() => { onTick(); }, delay); }); useEffect(() => { const id = onMount(); return () => { clearInterval(id); } }, []); return ( <>

Counter: {count}


Increment by: {increment}

Increment delay: {delay} ms

); } ``` ```css button { margin: 10px; } ``` -------------------------------- ### 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; } ``` -------------------------------- ### 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"}); ``` -------------------------------- ### 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; } ``` -------------------------------- ### React Component with Single Item Selection (Initial State) Source: https://react.dev/learn/choosing-the-state-structure This initial setup demonstrates a React component where only one item can be selected at a time, using a single `selectedId` state variable. It serves as the starting point for implementing multiple selection. ```js import { useState } from 'react'; import { letters } from './data.js'; import Letter from './Letter.js'; export default function MailClient() { const [selectedId, setSelectedId] = useState(null); // TODO: allow multiple selection const selectedCount = 1; function handleToggle(toggledId) { // TODO: allow multiple selection setSelectedId(toggledId); } return ( <>

Inbox

    {letters.map(letter => ( ))}

    You selected {selectedCount} letters

); } ``` ```js export default function Letter({ letter, onToggle, isSelected, }) { return (
  • ) } ``` ```js export const letters = [{ id: 0, subject: 'Ready for adventure?', isStarred: true, }, { id: 1, subject: 'Time to check in!', isStarred: false, }, { id: 2, subject: 'Festival Begins in Just SEVEN Days!', isStarred: false, }]; ``` ```css input { margin: 5px; } li { border-radius: 5px; } label { width: 100%; padding: 5px; display: inline-block; } .selected { background: #d2eaff; } ``` -------------------------------- ### 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"}); ``` -------------------------------- ### Configure React Compiler for React 17 or 18 Source: https://react.dev/reference/react-compiler/target After installing the runtime package, explicitly set the `target` option to '18' or '17' for compatibility with older React versions. This ensures the compiler generates code that uses the polyfill runtime, as demonstrated in the compiled output example. ```javascript // For React 18 { target: '18' } // For React 17 { target: '17' } ``` ```javascript // Compiled output uses the polyfill import { c as _c } from 'react-compiler-runtime'; ``` -------------------------------- ### Initialize React Application Source: https://react.dev/learn/add-react-to-an-existing-project Configures the HTML entry point and the main JavaScript file to render a React component into the DOM using createRoot. ```html My app
    ``` ```javascript import { createRoot } from 'react-dom/client'; // Clear the existing HTML content document.body.innerHTML = '
    '; // Render your React component instead const root = createRoot(document.getElementById('app')); root.render(

    Hello, world

    ); ``` -------------------------------- ### Configure React Compiler for Older React Versions (17/18) Source: https://react.dev/reference/react-compiler/configuration When working with React 17 or 18, the React Compiler requires specific setup. This involves installing the "react-compiler-runtime" package and explicitly setting the "target" configuration option to your React version (e.g., '18' or '17') to ensure proper compatibility. ```bash npm install react-compiler-runtime@latest ``` ```javascript { target: '18' // or '17' } ``` -------------------------------- ### Implement resumeAndPrerender in a Server Handler (JavaScript) Source: https://react.dev/reference/react-dom/static/resumeAndPrerender This example demonstrates how to integrate `resumeAndPrerender` into an asynchronous server handler. It imports the necessary function, retrieves `postponedState` from storage, and then calls `resumeAndPrerender` with a React component and configuration options. The resulting `prelude` stream is then used to construct and return an HTTP response with the generated HTML. ```javascript import { resumeAndPrerender } from 'react-dom/static'; import { getPostponedState } from 'storage'; async function handler(request, response) { const postponedState = getPostponedState(request); const { prelude } = await resumeAndPrerender(, postponedState, { bootstrapScripts: ['/main.js'] }); return new Response(prelude, { headers: { 'content-type': 'text/html' }, }); } ``` -------------------------------- ### React Component with Uncleaned Ref Callback (With Strict Mode) Source: https://react.dev/reference/react/StrictMode This example re-renders the same buggy React application, but this time wrapped in ``. In development, Strict Mode intentionally re-runs the ref callback's setup and cleanup cycle, causing the `console.log` messages to appear twice. This behavior helps highlight the missing cleanup logic, making the memory leak and its consequences more obvious to the developer. ```javascript import { createRoot } from 'react-dom/client'; import {StrictMode} from 'react'; import './styles.css'; import App from './App'; const root = createRoot(document.getElementById("root")); // βœ… Using StrictMode. root.render( ); ``` ```javascript import { useRef, useState } from "react"; export default function CatFriends() { const itemsRef = useRef([]); const [catList, setCatList] = useState(setupCatList); const [cat, setCat] = useState('neo'); function scrollToCat(index) { const list = itemsRef.current; const {node} = list[index]; node.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center", }); } const cats = catList.filter(c => c.type === cat) return ( <>