### Complete example of re-fetching data with use and Suspense Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/use.md Shows an interactive setup where App initiates data refetches inside startTransition and Albums suspends on the returned Promise using the use API. Includes caching and cache invalidation helpers. ```js import { Suspense, useState, useTransition } from 'react'; import { use } from 'react'; import { fetchData, refetchData } from './data.js'; export default function App() { const [albumsPromise, setAlbumsPromise] = useState( () => fetchData('/the-beatles/albums') ); const [isPending, startTransition] = useTransition(); function handleRefresh() { startTransition(() => { setAlbumsPromise(refetchData('/the-beatles/albums')); }); } return ( <>
}>
); } function Albums({ albumsPromise }) { const albums = use(albumsPromise); return ( ); } function Loading() { return

Loading...

; } ``` ```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); } export function refetchData(url) { cache.delete(url); return fetchData(url); } async function getData(url) { if (url.startsWith('/the-beatles/albums')) { return await getAlbums(); } else { throw Error('Not implemented'); } } async function getAlbums() { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 1000); }); return [{ id: 13, title: 'Let It Be', year: 1970 }, { id: 12, title: 'Abbey Road', year: 1969 }, { id: 11, title: 'Yellow Submarine', year: 1969 }, { id: 10, title: 'The Beatles', year: 1968 }, { id: 9, title: 'Magical Mystery Tour', year: 1967 }]; } ``` ```css button { margin-bottom: 10px; } ``` -------------------------------- ### Focus search field challenge setup Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/manipulating-the-dom-with-refs.md Initial setup consisting of separate App, SearchButton, and SearchInput components before connecting them via refs and event handlers. ```javascript import SearchButton from './SearchButton.js'; import SearchInput from './SearchInput.js'; export default function Page() { return ( <> ); } ``` ```javascript export default function SearchButton() { return ( ); } ``` ```javascript export default function SearchInput() { return ( ); } ``` ```css button { display: block; margin-bottom: 10px; } ``` -------------------------------- ### Complete Counter example with useReducer Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/useReducer.md An interactive example demonstrating how a counter component uses useReducer to handle state updates and render the updated UI. ```javascript import { useReducer } from 'react'; function reducer(state, action) { if (action.type === 'incremented_age') { return { age: state.age + 1 }; } throw Error('Unknown action.'); } export default function Counter() { const [state, dispatch] = useReducer(reducer, { age: 42 }); return ( <>

Hello! You are {state.age}.

); } ``` ```css button { display: block; margin-top: 10px; } ``` -------------------------------- ### Complete Leaflet map widget portal integration example Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/createPortal.md Full multi-file example showing how to mount a Leaflet map widget and render a React component inside its popup using createPortal. ```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; } ``` -------------------------------- ### Video player challenge initial setup Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/manipulating-the-dom-with-refs.md Initial state-only implementation for toggling a video player before adding a DOM ref. ```jsx import { useState, useRef } from 'react'; export default function VideoPlayer() { const [isPlaying, setIsPlaying] = useState(false); function handleClick() { const nextIsPlaying = !isPlaying; setIsPlaying(nextIsPlaying); } return ( <> ) } ``` ```css button { display: block; margin-bottom: 20px; } ``` -------------------------------- ### Install React and React DOM Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/add-react-to-an-existing-project.md Installs the react and react-dom packages into your project using npm to prepare for rendering React components. ```shell npm install react react-dom ``` -------------------------------- ### Install React Compiler using npm Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md Installs the React Compiler Babel plugin as a developer dependency using npm. ```bash npm install -D babel-plugin-react-compiler@latest ``` -------------------------------- ### Install React Compiler using Yarn Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md Installs the React Compiler Babel plugin as a developer dependency using Yarn. ```bash yarn add -D babel-plugin-react-compiler@latest ``` -------------------------------- ### Install React Compiler using pnpm Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md Installs the React Compiler Babel plugin as a developer dependency using pnpm. ```bash pnpm install -D babel-plugin-react-compiler@latest ``` -------------------------------- ### Set up Messenger component with useReducer Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/extracting-state-logic-into-a-reducer.md Initial setup of the Messenger component before implementing input reset logic on send. ```javascript import { useReducer } from 'react'; import Chat from './Chat.js'; import ContactList from './ContactList.js'; import { initialState, messengerReducer } from './messengerReducer'; export default function Messenger() { const [state, dispatch] = useReducer(messengerReducer, initialState); const message = state.message; const contact = contacts.find((c) => c.id === state.selectedId); return (
); } const contacts = [ {id: 0, name: 'Taylor', email: 'taylor@mail.com'}, {id: 1, name: 'Alice', email: 'alice@mail.com'}, {id: 2, name: 'Bob', email: 'bob@mail.com'}, ]; ``` -------------------------------- ### Focus search field challenge initial setup Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/manipulating-the-dom-with-refs.md Initial markup for a search button and input field before wiring up focus with a ref. ```jsx export default function Page() { return ( <> ); } ``` ```css button { display: block; margin-bottom: 10px; } ``` -------------------------------- ### Starter code for extracting useInterval Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/reusing-logic-with-custom-hooks.md Initial setup containing the Counter component, the monolithic `useCounter` implementation, and an empty `useInterval.js` file. ```javascript import { useCounter } from './useCounter.js'; export default function Counter() { const count = useCounter(1000); return

Seconds passed: {count}

; } ``` ```javascript import { useState, useEffect } from 'react'; export function useCounter(delay) { const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { setCount(c => c + 1); }, delay); return () => clearInterval(id); }, [delay]); return count; } ``` ```javascript // Write your Hook here! ``` -------------------------------- ### Install babel-plugin-react-compiler Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-compiler/compiling-libraries.md Adds React Compiler as a development dependency to the library build process. ```bash npm install -D babel-plugin-react-compiler@latest ``` -------------------------------- ### Define mock caching fetcher and styling for Suspense examples Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md Provides mock asynchronous data-fetching utilities with simulated delay and basic CSS styles for loading state panels and shimmer effects. ```javascript // 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 [{ id: 13, title: 'Let It Be', year: 1970 }, { id: 12, title: 'Abbey Road', year: 1969 }, { id: 11, title: 'Yellow Submarine', year: 1969 }, { id: 10, title: 'The Beatles', year: 1968 }, { id: 9, title: 'Magical Mystery Tour', year: 1967 }, { id: 8, title: 'Sgt. Pepper\'s Lonely Hearts Club Band', year: 1967 }, { id: 7, title: 'Revolver', year: 1966 }, { id: 6, title: 'Rubber Soul', year: 1965 }, { id: 5, title: 'Help!', year: 1965 }, { id: 4, title: 'Beatles For Sale', year: 1964 }, { id: 3, title: 'A Hard Day\'s Night', year: 1964 }, { id: 2, title: 'With The Beatles', year: 1963 }, { id: 1, title: 'Please Please Me', year: 1963 }]; } ``` ```css .bio { font-style: italic; } .panel { border: 1px solid #aaa; border-radius: 6px; margin-top: 20px; padding: 10px; } .glimmer-panel { border: 1px dashed #aaa; background: linear-gradient(90deg, rgba(221,221,221,1) 0%, rgba(255,255,255,1) 100%); border-radius: 6px; margin-top: 20px; padding: 10px; } .glimmer-line { display: block; width: 60%; height: 20px; margin: 10px; border-radius: 4px; background: #f0f0f0; } ``` -------------------------------- ### Resetting Suspense boundary on profile navigation example Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md Demonstrates switching profiles inside a transition with Suspense keyed by user id to display loading fallback instead of the previous user's bio. ```javascript import { useState } from 'react'; import ProfilePage from './ProfilePage.js'; export default function App() { const [show, setShow] = useState(false); if (show) { return ; } return ( ); } ``` ```javascript import { Suspense, useState, startTransition } from 'react'; import Bio from './Bio.js'; import { fetchBio } from './data.js'; export default function ProfilePage() { const [user, setUser] = useState(() => ({ id: 'alice', bioPromise: fetchBio('alice'), })); function navigate(id) { startTransition(() => { setUser({ id, bioPromise: fetchBio(id) }); }); } return ( <> ⌛ Loading profile...

}>
); } ``` ```javascript import { use } from 'react'; export default function Bio({ bioPromise }) { const bio = use(bioPromise); return

{bio}

; } ``` ```javascript // Note: the way you would do data fetching depends on // the framework that you use together with Suspense. export async function fetchBio(userId) { // Add a fake delay to make waiting noticeable. await new Promise(resolve => { setTimeout(resolve, 1500); }); return userId === 'alice' ? 'Alice is a photographer and traveler.' : 'Bob collects vintage synthesizers.'; } ``` ```css button { margin-right: 8px; } ``` -------------------------------- ### Coordinating data fetching across multiple components in a Suspense sandbox Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md An interactive Sandpack example where Biography and Albums components fetch data concurrently under a shared Suspense boundary and pop in together. ```js import { useState } from 'react'; import ArtistPage from './ArtistPage.js'; export default function App() { const [show, setShow] = useState(false); if (show) { return ( ); } else { 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 Loading() { return

🌀 Loading...

; } ``` ```js export default function Panel({ children }) { return (
{children}
); } ``` ```js import {use} from 'react'; import { fetchData } from './data.js'; export default function Biography({ artistId }) { const bio = use(fetchData(`/${artistId}/bio`)); return (

{bio}

); } ``` ```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 // 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, 1500); }); 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 [{ id: 13, title: 'Let It Be', year: 1970 }, { id: 12, title: 'Abbey Road', year: 1969 }, { id: 11, title: 'Yellow Submarine', year: 1969 }, { id: 10, title: 'The Beatles', year: 1968 }, { id: 9, title: 'Magical Mystery Tour', year: 1967 }, { id: 8, title: 'Sgt. Pepper\'s Lonely Hearts Club Band', year: 1967 }, { id: 7, title: 'Revolver', year: 1966 }, { id: 6, title: 'Rubber Soul', year: 1965 }, { id: 5, title: 'Help!', year: 1965 }, { id: 4, title: 'Beatles For Sale', year: 1964 }, { id: 3, title: 'A Hard Day\'s Night', year: 1964 }, { id: 2, title: 'With The Beatles', year: 1963 }, { id: 1, title: 'Please Please Me', year: 1963 }]; } ``` ```css .bio { font-style: italic; } .panel { border: 1px solid #aaa; border-radius: 6px; margin-top: 20px; padding: 10px; } ``` -------------------------------- ### Thumbnail and Video presentation component Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/ViewTransition.md Defines the Video and Thumbnail display components used within the list item reorder examples. ```javascript function Thumbnail({video}) { return (