### Complete Example: Map Widget Integration Source: https://react.dev/reference/react-dom/createPortal A full example demonstrating the integration of React components with a non-React map widget using `createPortal`. Includes setup for Leaflet map and popup. ```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; } ``` -------------------------------- ### Complete example using createElement Source: https://react.dev/reference/react/createElement A full example demonstrating the creation of a greeting component and its rendering using `createElement`. Includes both the component definition and the app structure. ```javascript 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; } ``` -------------------------------- ### App Component Setup Source: https://react.dev/reference/react/useCallback Sets up the main App component with a theme toggle and renders the ProductPage. No specific setup is required beyond standard React. ```javascript import { useState } from 'react'; import ProductPage from './ProductPage.js'; export default function App() { const [isDark, setIsDark] = useState(false); return ( <>
); } ``` -------------------------------- ### Install React Compiler Plugin Source: https://react.dev/reference/react-compiler/compiling-libraries Install the Babel plugin as a development dependency. ```bash npm install -D babel-plugin-react-compiler@latest ``` -------------------------------- ### Sandpack example: App component Source: https://react.dev/reference/react/cloneElement Main entry point for the interactive List example. ```js import List from './List.js'; import Row from './Row.js'; import { products } from './data.js'; export default function App() { return ( {products.map(product => )} ); } ``` -------------------------------- ### Example: TodosApp component using useSyncExternalStore Source: https://react.dev/reference/react/useSyncExternalStore This example demonstrates connecting a React component to an external `todosStore`. It uses `useSyncExternalStore` to get the latest todos and allows adding new todos via the store's `addTodo` method. ```javascript import { useSyncExternalStore } from 'react'; import { todosStore } from './todoStore.js'; export default function TodosApp() { const todos = useSyncExternalStore(todosStore.subscribe, todosStore.getSnapshot); return ( <>
); } ``` -------------------------------- ### Complete Example: Themed Application with Context Source: https://react.dev/reference/react/useContext A full example demonstrating a React application with theming. It includes context creation, providing theme values, and consuming them in different components like Panel and Button. The CSS styles are also included. ```javascript import { createContext, useContext } from 'react'; const ThemeContext = createContext(null); export default function MyApp() { return (
) } function Form() { return ( ); } function Panel({ title, children }) { const theme = useContext(ThemeContext); const className = 'panel-' + theme; return (

{title}

{children}
) } function Button({ children }) { const theme = useContext(ThemeContext); const className = 'button-' + theme; return ( ); } ``` ```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; } ``` -------------------------------- ### Preiniting in an event handler Source: https://react.dev/reference/react-dom/preinit Example of calling preinit within an event handler to start resource loading earlier. ```APIDOC ## Preiniting in an event handler ### Description Call `preinit` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. ### Method `preinit` ### Endpoint N/A (Client-side function) ### Parameters * `href` (string): The URL of the resource to preinit. * `options` (object): Configuration options for the resource. ### Request Example ```js import { preinit } from 'react-dom'; function CallToAction() { const onClick = () => { preinit("https://example.com/wizardStyles.css", {as: "style"}); startWizard(); } return ( ); } ``` ``` -------------------------------- ### Example Usage of useEffect Source: https://react.dev/reference/react/useEffect An example demonstrating how to use the useEffect Hook to set up and clean up a connection to an external system. ```APIDOC ## Example: Setting up and cleaning up a connection ### Description This example shows how to use `useEffect` to establish a connection to a server and disconnect when the component unmounts or when dependencies change. ### Method `useEffect(setup, dependencies?) ### Endpoint N/A (This is a React Hook, not an API endpoint) ### Request Example ```javascript import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; function ChatRoom({ roomId }) { const [serverUrl, setServerUrl] = useState('https://localhost:1234'); useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => { connection.disconnect(); }; }, [serverUrl, roomId]); // ... } ``` ### Response N/A (This is a React Hook, not an API endpoint that returns data) ``` -------------------------------- ### Complete example using JSX Source: https://react.dev/reference/react/createElement A full example of the greeting component and app structure written using JSX syntax. This provides a direct comparison to the `createElement` version. ```javascript function Greeting({ name }) { return (

Hello {name}. Welcome!

); } export default function App() { return ; } ``` ```css .greeting { color: darkgreen; font-family: Georgia; } ``` -------------------------------- ### Counter Example Source: https://react.dev/reference/react/useState A practical example demonstrating how to use `useState` to create a simple counter component. ```APIDOC ## Counter Example ### Description This example shows a basic counter component where the `count` state variable is incremented each time a button is clicked. ### Method Function Call ### Endpoint N/A (Client-side Hook) ### Code Example ```javascript import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); } return ( ); } ``` ### Response #### Success Response (UI Update) - The button text updates to reflect the current `count` value. #### Response Example (UI) Initially: "You pressed me 0 times" After clicking once: "You pressed me 1 times" ``` -------------------------------- ### Example: Implementing an external store (todoStore.js) Source: https://react.dev/reference/react/useSyncExternalStore This JavaScript file implements a simple external store for managing todos. It includes functions to add todos, subscribe to changes, and get the current snapshot of the todo list. This pattern is useful for integrating with non-React state management libraries. ```javascript // 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(); } } ``` -------------------------------- ### Usage Examples Source: https://react.dev/reference/react-dom/prefetchDNS Demonstrates how to use the prefetchDNS function in different scenarios. ```APIDOC ### Prefetching DNS when rendering Call `prefetchDNS` when rendering a component if you anticipate its children will load external resources from a specific host. ```javascript import { prefetchDNS } from 'react-dom'; function AppRoot() { prefetchDNS("https://example.com"); return ...; } ``` ### Prefetching DNS in an event handler Call `prefetchDNS` within an event handler before navigating to a new page or state that requires external resources. This initiates the DNS lookup process earlier. ```javascript import { prefetchDNS } from 'react-dom'; function CallToAction() { const onClick = () => { prefetchDNS('http://example.com'); startWizard(); } return ( ); } ``` ``` -------------------------------- ### Basic preinitModule usage Source: https://react.dev/reference/react-dom/preinitModule A simple example showing how to call preinitModule to fetch and evaluate a module. ```javascript preinitModule("https://example.com/module.js", {as: "script"}); ``` -------------------------------- ### Preloading a stylesheet Source: https://react.dev/reference/react-dom/preload Example of how to preload a CSS file. ```APIDOC ## POST /preload/stylesheet ### Description Preloads a stylesheet. ### Method POST ### Endpoint /preload/stylesheet ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **href** (string) - Required - The URL of the stylesheet to preload. - **options** (object) - Required - An object containing options for preloading. - **as** (string) - Required - Must be set to `"style"`. ### Request Example ```json { "href": "https://example.com/style.css", "options": { "as": "style" } } ``` ### Response #### Success Response (200) `preload` returns nothing. #### Response Example (No response body for success) ``` -------------------------------- ### Sandpack example: CSS styles Source: https://react.dev/reference/react/useDeferredValue Styling for the list and items in the deferred rendering example. ```css .items { padding: 0; } .item { list-style: none; display: block; height: 40px; padding: 5px; margin-top: 10px; border-radius: 4px; border: 1px solid #aaa; } ``` -------------------------------- ### Usage Example: Rendering Components in Tests Source: https://react.dev/reference/react/act Example demonstrating how to use `act` to render and test a React component. ```APIDOC ## Rendering components in tests To test the render output of a component, wrap the render inside `act()`: ```js import {act} from 'react'; import ReactDOMClient from 'react-dom/client'; import Counter from './Counter'; it ('can render and update a counter', async () => { container = document.createElement('div'); document.body.appendChild(container); // ✅ Render the component inside act(). await act(() => { ReactDOMClient.createRoot(container).render(); }); const button = container.querySelector('button'); const label = container.querySelector('p'); expect(label.textContent).toBe('You clicked 0 times'); expect(document.title).toBe('You clicked 0 times'); }); ``` Here, we create a container, append it to the document, and render the `Counter` component inside `act()`. This ensures that the component is rendered and its effects are applied before making assertions. Using `act` ensures that all updates have been applied before we make assertions. ``` -------------------------------- ### Preiniting a stylesheet Source: https://react.dev/reference/react-dom/preinit Example of preiniting a stylesheet with precedence when rendering a component. ```APIDOC ## Preiniting a stylesheet ### Description Call `preinit` when rendering a component to preinit a stylesheet. This ensures the stylesheet is downloaded and applied. ### Method `preinit` ### Endpoint N/A (Client-side function) ### Parameters * `href` (string): The URL of the stylesheet to preinit. * `options` (object): Configuration options. * `as` (string): Must be `"style"`. * `precedence` (string): Required. Controls the order of stylesheets. Possible values: `reset`, `low`, `medium`, `high`. ### Request Example ```js import { preinit } from 'react-dom'; function AppRoot() { preinit("https://example.com/style.css", {as: "style", precedence: "medium"}); return ...; } ``` ### Notes * The `precedence` option is required and lets you control the order of stylesheets within the document. * If you want to download the stylesheet but not to insert it into the document right away, use [`preload`](/reference/react-dom/preload) instead. ``` -------------------------------- ### Modal Example using createPortal Source: https://react.dev/reference/react-dom/createPortal A complete React component example demonstrating how to use createPortal to render a modal dialog into the document body, allowing it to appear outside its parent container. ```jsx import { createPortal } from 'react-dom'; function MyComponent() { return (

This child is placed in the parent div.

{createPortal(

This child is placed in the document body.

, document.body )}
); } ``` -------------------------------- ### Use a React component Source: https://react.dev/reference/rsc/use-client An example of importing and rendering a component within another component. ```js import MyComponent from './MyComponent'; function App() { // This is a usage of a component return ; } ``` -------------------------------- ### Interactive Example: Toggling Element Visibility with ViewTransition Source: https://react.dev/reference/react/ViewTransition This example demonstrates how to toggle the visibility of a video item using a button. The `startTransition` API is used to ensure the UI remains responsive during the state update, triggering enter/exit animations for the `` component. ```javascript import {ViewTransition, useState, startTransition} from 'react'; import {Video} from './Video'; import videos from './data'; function Item() { return ( ); } export default function Component() { const [showItem, setShowItem] = useState(false); return ( <> {showItem ? : null} ); } ``` -------------------------------- ### Preloading an external script Source: https://react.dev/reference/react-dom/preload Example of how to preload an external JavaScript file. ```APIDOC ## POST /preload/script ### Description Preloads an external script file. ### Method POST ### Endpoint /preload/script ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **href** (string) - Required - The URL of the script to preload. - **options** (object) - Required - An object containing options for preloading. - **as** (string) - Required - Must be set to `"script"`. ### Request Example ```json { "href": "https://example.com/script.js", "options": { "as": "script" } } ``` ### Response #### Success Response (200) `preload` returns nothing. #### Response Example (No response body for success) ``` -------------------------------- ### Symmetrical Setup and Cleanup in useEffect Source: https://react.dev/reference/react/useEffect Ensure your cleanup logic is symmetrical to the setup logic, undoing whatever the setup did. This example shows a connection being established and then disconnected. ```javascript useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); return () => { connection.disconnect(); }; }, [serverUrl, roomId]); ``` -------------------------------- ### React app setup with StrictMode Source: https://react.dev/reference/react/StrictMode Boilerplate code for a React application using createRoot and StrictMode. ```javascript import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './styles.css'; import App from './App'; const root = createRoot(document.getElementById("root")); root.render( ); ``` -------------------------------- ### Preloading in an event handler Source: https://react.dev/reference/react-dom/preinitModule Example of calling preinitModule within an event handler to start module loading before a transition. ```APIDOC ## Preloading in an event handler ### Description Call `preinitModule` in an event handler before transitioning to a page or state where the module will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. ### Method `preinitModule` ### Endpoint N/A (Client-side function call) ### Parameters See `preinitModule(href, options)` documentation. ### Request Example ```javascript import { preinitModule } from 'react-dom'; function CallToAction() { const onClick = () => { preinitModule("https://example.com/module.js", {as: "script"}); startWizard(); } return ( ); } ``` ### Response N/A ``` -------------------------------- ### Initialize a React root Source: https://react.dev/reference/react-dom/client/createRoot Basic syntax for creating a root instance. ```js const root = createRoot(domNode, options?) ``` -------------------------------- ### Full component with CSS and dynamic styles Source: https://react.dev/reference/react-dom/components/common A complete example demonstrating component structure, dynamic styles, and external CSS. ```js import Avatar from './Avatar.js'; const user = { name: 'Hedy Lamarr', imageUrl: 'https://react.dev/images/docs/scientists/yXOvdOSs.jpg', imageSize: 90, }; export default function App() { return ; } ``` ```js export default function Avatar({ user }) { return ( {'Photo ); } ``` ```css .avatar { border-radius: 50%; } ``` -------------------------------- ### Basic resumeAndPrerender Usage Source: https://react.dev/reference/react-dom/static/resumeAndPrerender This is a basic example of how to call resumeAndPrerender, showing the expected arguments and return values. ```javascript const { prelude,postpone } = await resumeAndPrerender(reactNode, postponedState, options?) ``` -------------------------------- ### Focus Input with useRef Source: https://react.dev/reference/react/useRef This example demonstrates focusing an input element when a button is clicked. It utilizes `useRef` to get a direct reference to the input DOM node. ```javascript import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> ); } ``` -------------------------------- ### Preconnecting in an event handler Source: https://react.dev/reference/react-dom/preconnect Call `preconnect` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. ```APIDOC ## Preconnecting in an event handler ### Description Call `preconnect` in an event handler before transitioning to a page or state where external resources will be needed. This gets the process started earlier than if you call it during the rendering of the new page or state. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript import { preconnect } from 'react-dom'; function CallToAction() { const onClick = () => { preconnect('http://example.com'); startWizard(); } return ( ); } ``` ### Response N/A ``` -------------------------------- ### Start a Non-Blocking Transition Source: https://react.dev/reference/react/useTransition Wrap state updates and side effects within `startTransition` to perform them in the background without blocking user interactions. This example shows updating quantity after an API call. ```javascript import {useState, useTransition} from 'react'; import {updateQuantity} from './api'; function CheckoutForm() { const [isPending, startTransition] = useTransition(); const [quantity, setQuantity] = useState(1); function onSubmit(newQuantity) { startTransition(async function () { const savedQuantity = await updateQuantity(newQuantity); startTransition(() => { setQuantity(savedQuantity); }); }); } // ... ``` -------------------------------- ### Callback Ref Cleanup Log Output Source: https://react.dev/reference/react/StrictMode Example console output demonstrating the effect of Strict Mode on callback refs. It shows the setup, cleanup, and re-setup cycles, confirming that the cleanup function is working correctly and preventing memory leaks. ```text ... ✅ Adding animal to the map. Total animals: 10 ... ❌ Removing animal from the map. Total animals: 0 ... ✅ Adding animal to the map. Total animals: 10 ``` -------------------------------- ### Complete Example: Conditional Context and Theming Source: https://react.dev/reference/react/use A full React application demonstrating context provision, conditional reading of context using `use`, and applying theme-based CSS classes to components. ```javascript 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; } ``` -------------------------------- ### Eagerly connect to a server Source: https://react.dev/reference/react-dom/preconnect Use `preconnect` to establish a connection to a server you expect to load resources from. This can be called directly. ```javascript preconnect("https://example.com"); ``` -------------------------------- ### Implement prerender and resume logic Source: https://react.dev/reference/react-dom/server/resume Demonstrates the lifecycle of prerendering an app, handling postponed states, and resuming rendering before hydration. ```javascript import { flushReadableStreamToFrame, getUser, Postponed, sleep, } from "./demo-helpers"; import { StrictMode, Suspense, use, useEffect } from "react"; import { prerender } from "react-dom/static"; import { resume } from "react-dom/server"; import { hydrateRoot } from "react-dom/client"; function Header() { return
Me and my descendants can be prerendered
; } const { promise: cookies, resolve: resolveCookies } = Promise.withResolvers(); function Main() { const { sessionID } = use(cookies); const user = getUser(sessionID); useEffect(() => { console.log("reached interactivity!"); }, []); return (
Hello, {user.name}!
); } function Shell({ children }) { // In a real app, this is where you would put your html and body. // We're just using tags here we can include in an existing body for demonstration purposes return ( {children} ); } function App() { return (
); } async function main(frame) { // Layer 1 const controller = new AbortController(); const prerenderedApp = prerender(, { signal: controller.signal, onError(error) { if (error instanceof Postponed) { } else { console.error(error); } }, }); // We're immediately aborting in a macrotask. // Any data fetching that's not available synchronously, or in a microtask, will not have finished. setTimeout(() => { controller.abort(new Postponed()); }); const { prelude, postponed } = await prerenderedApp; await flushReadableStreamToFrame(prelude, frame); // Layer 2 // Just waiting here for demonstration purposes. // In a real app, the prelude and postponed state would've been serialized in Layer 1 and Layer would deserialize them. // The prelude content could be flushed immediated as plain HTML while // React is continuing to render from where the prerender left off. await sleep(2000); // You would get the cookies from the incoming HTTP request resolveCookies({ sessionID: "abc" }); const stream = await resume(, postponed); await flushReadableStreamToFrame(stream, frame); // Layer 3 // Just waiting here for demonstration purposes. await sleep(2000); hydrateRoot(frame.contentWindow.document, ); } main(document.getElementById("container")); ``` -------------------------------- ### Initialize ChatRoom application Source: https://react.dev/reference/react/StrictMode Entry point for the React application. ```javascript import { createRoot } from 'react-dom/client'; import './styles.css'; import App from './App'; const root = createRoot(document.getElementById("root")); root.render(); ``` -------------------------------- ### Resume rendering with imports and piping Source: https://react.dev/reference/react-dom/server/resume This example demonstrates how to import `resume` and use it within a request handler to stream the rendered output to a writable stream. Ensure `getPostponedState` is correctly implemented to retrieve the necessary state. ```javascript import { resume } from 'react-dom/server'; import {getPostponedState} from './storage'; async function handler(request, writable) { const postponed = await getPostponedState(request); const resumeStream = await resume(, postponed); return resumeStream.pipeTo(writable) ``` -------------------------------- ### Install React Compiler Runtime Source: https://react.dev/reference/react-compiler/compiling-libraries Install the runtime package for libraries supporting React versions below 19. ```bash npm install react-compiler-runtime@latest ``` -------------------------------- ### Insecure Secret Handling Example Source: https://react.dev/reference/react/experimental_taintUniqueValue An example of an insecure pattern where a server-side secret is passed directly to a Client Component. ```javascript export async function Dashboard(props) { // DO NOT DO THIS return ; } ``` ```javascript "use client"; import {useEffect} from '...' export async function Overview({ password }) { useEffect(() => { const headers = { Authorization: password }; fetch(url, { headers }).then(...); }, [password]); ... } ``` -------------------------------- ### State-preserving animation example Source: https://react.dev/reference/react/ViewTransition A complete example showing how Activity preserves internal component state during visibility toggles. ```js import { Activity, ViewTransition, useState, startTransition } from 'react'; export default function App() { const [show, setShow] = useState(true); return (
); } function Toggle({show, setShow}) { return ( ) } function Counter() { const [count, setCount] = useState(0); return (

Counter

Count: {count}

); } ``` ```css .layout { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; min-height: 200px; } .counter { padding: 15px; background: #f0f4f8; border-radius: 8px; width: 200px; } .counter h2 { margin: 0 0 10px 0; font-size: 16px; } .counter p { margin: 0 0 10px 0; } .toggle { padding: 8px 16px; border: 1px solid #ccc; border-radius: 6px; background: #f0f8ff; cursor: pointer; font-size: 14px; } .toggle:hover { background: #e0e8ff; } .counter button { padding: 4px 12px; border: 1px solid #ccc; border-radius: 4px; background: white; cursor: pointer; } ``` ```json { "dependencies": { "react": "canary", "react-dom": "canary", "react-scripts": "latest" } } ``` -------------------------------- ### Install React Compiler Runtime for Older Projects Source: https://react.dev/reference/react-compiler/configuration For React 17/18 projects, install the 'react-compiler-runtime' package using npm. ```bash npm install react-compiler-runtime@latest ``` -------------------------------- ### Initialize useReducer with createInitialState function Source: https://react.dev/reference/react/useReducer This example shows how to initialize useReducer by passing a function that creates the initial state. This function runs only once on initial render. ```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 import source paths Source: https://react.dev/reference/react-compiler/gating Examples of correct and incorrect module resolution paths for the source property. ```js // ❌ Wrong: Relative to babel.config.js { source: './src/flags', importSpecifierName: 'flag' } // ✅ Correct: Module resolution path { source: '@myapp/feature-flags', importSpecifierName: 'flag' } // ✅ Also correct: Absolute path from project root { source: './src/utils/flags', importSpecifierName: 'flag' } ``` -------------------------------- ### Invalid Component Purity Examples Source: https://react.dev/reference/eslint-plugin-react-hooks/lints/purity Examples of components that violate purity by calling impure functions directly during the render phase. ```js // ❌ Math.random() in render function Component() { const id = Math.random(); // Different every render return
Content
; } // ❌ Date.now() for values function Component() { const timestamp = Date.now(); // Changes every render return
Created at: {timestamp}
; } ``` -------------------------------- ### Install React Compiler Runtime Source: https://react.dev/reference/react-compiler/target For React 17 and 18, install the `react-compiler-runtime` package using npm. This is required for the polyfill runtime. ```bash npm install react-compiler-runtime@latest ``` ```bash npm install react-compiler-runtime@latest ``` -------------------------------- ### Full Suspense-enabled router example Source: https://react.dev/reference/react/useTransition A complete implementation of a router using Suspense and Transitions to manage loading states. ```js import { Suspense, useState, useTransition } from 'react'; import IndexPage from './IndexPage.js'; import ArtistPage from './ArtistPage.js'; import Layout from './Layout.js'; export default function App() { return ( }> ); } function Router() { const [page, setPage] = useState('/'); const [isPending, startTransition] = useTransition(); function navigate(url) { startTransition(() => { setPage(url); }); } let content; if (page === '/') { content = ( ); } else if (page === '/the-beatles') { content = ( ); } return ( {content} ); } function BigSpinner() { return

🌀 Loading...

; } ``` ```js export default function Layout({ children, isPending }) { return (
Music Browser
{children}
); } ``` ```js export default function IndexPage({ navigate }) { return ( ); } ``` ```js import { Suspense } from 'react'; import Albums from './Albums.js'; import Biography from './Biography.js'; import Panel from './Panel.js'; export default function ArtistPage({ artist }) { return ( <>

{artist.name}

}> ); } function AlbumsGlimmer() { return (
); } ``` ```js import {use} from 'react'; import { fetchData } from './data.js'; export default function Albums({ artistId }) { const albums = use(fetchData(`/${artistId}/albums`)); return (
    {albums.map(album => (
  • {album.title} ({album.year})
  • ))}
); } ``` ```js import {use} from 'react'; import { fetchData } from './data.js'; export default function Biography({ artistId }) { const bio = use(fetchData(`/${artistId}/bio`)); return (

{bio}

); } ``` ```js export default function Panel({ children }) { return (
{children}
); } ``` ```js // Note: the way you would do data fetching depends on // the framework that you use together with Suspense. // Normally, the caching logic would be inside a framework. let cache = new Map(); export function fetchData(url) { if (!cache.has(url)) { cache.set(url, getData(url)); } return cache.get(url); } async function getData(url) { if (url === '/the-beatles/albums') { return await getAlbums(); } else if (url === '/the-beatles/bio') { return await getBio(); } else { throw Error('Not implemented'); } } async function getBio() { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 500); }); return `The Beatles were an English rock band, formed in Liverpool in 1960, that comprised John Lennon, Paul McCartney, George Harrison and Ringo Starr.`; } async function getAlbums() { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 3000); }); return [{ ``` -------------------------------- ### Blog component with multiple posts using Fragment Source: https://react.dev/reference/react/Fragment This example demonstrates rendering multiple `Post` components within a Fragment. It shows how Fragments can be used to group sibling elements in a parent component. ```javascript export default function Blog() { return ( <> ) } function Post({ title, body }) { return ( <> ); } function PostTitle({ title }) { return

{title}

} function PostBody({ body }) { return (

{body}

); } ``` -------------------------------- ### Incorrect Hook Usage Examples Source: https://react.dev/reference/rules/rules-of-hooks Examples of invalid Hook calls, such as inside conditions, loops, event handlers, or class components. ```js function Bad({ cond }) { if (cond) { // 🔴 Bad: inside a condition (to fix, move it outside!) const theme = useContext(ThemeContext); } // ... } function Bad() { for (let i = 0; i < 10; i++) { // 🔴 Bad: inside a loop (to fix, move it outside!) const theme = useContext(ThemeContext); } // ... } function Bad({ cond }) { if (cond) { return; } // 🔴 Bad: after a conditional return (to fix, move it before the return!) const theme = useContext(ThemeContext); // ... } function Bad() { function handleClick() { // 🔴 Bad: inside an event handler (to fix, move it outside!) const theme = useContext(ThemeContext); } // ... } function Bad() { const style = useMemo(() => { // 🔴 Bad: inside useMemo (to fix, move it outside!) const theme = useContext(ThemeContext); return createStyle(theme); }); // ... } class Bad extends React.Component { render() { // 🔴 Bad: inside a class component (to fix, write a function component instead of a class!) useEffect(() => {}) // ... } } function Bad() { try { // 🔴 Bad: inside try/catch/finally block (to fix, move it outside!) const [x, setX] = useState(0); } catch { const [x, setX] = useState(1); } } ``` -------------------------------- ### Usage Example: Server-Side Rendering Source: https://react.dev/reference/react-dom/server/renderToStaticMarkup Example of how to use renderToStaticMarkup within a server-side route handler to send static HTML to the client. ```APIDOC ## POST /api/render ### Description This endpoint demonstrates how to use `renderToStaticMarkup` in a server-side route handler to generate and return static HTML. ### Method POST ### Endpoint `/api/render` ### Request Body * `reactNode` (ReactNode) - Required - The React node to render. ### Request Example ```json { "reactNode": "" } ``` ### Response #### Success Response (200) - `html` (string) - The rendered static HTML string. ### Response Example ```javascript // Assuming a backend framework like Express.js app.post('/api/render', (request, response) => { const { reactNode } = request.body; const html = renderToStaticMarkup(reactNode); response.send(html); }); ``` ``` -------------------------------- ### Customize animations using `View Transition` Class Source: https://react.dev/reference/react/addTransitionType Example demonstrating how to customize animations for `ViewTransition` based on transition types using the `enter` prop. ```APIDOC ## PUT /api/users/{id} ### Description Updates an existing user's information. The user is identified by their ID, and the updated fields are provided in the request body. ### Method PUT ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - `id` (string) - Required - The unique identifier of the user to update. #### Query Parameters N/A #### Request Body - `email` (string) - Optional - The updated email address for the user. - `password` (string) - Optional - The updated password for the user. ### Request Example ```json { "email": "john.doe.updated@example.com" } ``` ### Response #### Success Response (200 OK) - `id` (string) - The unique identifier of the updated user. - `username` (string) - The username of the updated user. - `email` (string) - The updated email address of the user. #### Response Example ```json { "id": "user-12345", "username": "johndoe", "email": "john.doe.updated@example.com" } ``` ```