### 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 (
{albums.map(album => (
{album.title} ({album.year})
))}
);
}
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 (
);
}
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 (
);
}
export function Video({video}) {
return (
{video.title}
{video.description}
);
}
```
--------------------------------
### Indicating transition state during navigation with useTransition
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
Replace startTransition with useTransition to access the isPending boolean for visual loading indicators during page navigation. In this example, isPending dims the header opacity while new data loads within Suspense boundaries.
```javascript
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
);
}
```
```javascript
export default function IndexPage({ navigate }) {
return (
);
}
```
```javascript
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 (
);
}
```
```javascript
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})
))}
);
}
```
```javascript
import {use} from 'react';
import { fetchData } from './data.js';
export default function Biography({ artistId }) {
const bio = use(fetchData(`/${artistId}/bio`));
return (
{bio}
);
}
```
```javascript
export default function Panel({ children }) {
return (
{children}
);
}
```
--------------------------------
### Implement symmetrical setup and cleanup logic in useEffect
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/useEffect.md
Structure cleanup logic so that it is symmetrical to setup logic by stopping or undoing whatever setup performed. In this example, the cleanup disconnects the connection established during setup.
```javascript
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
```
--------------------------------
### Full client-side application setup
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/client/createRoot.md
Configures an HTML target container, mounts the application at startup with createRoot, and defines interactive React components.
```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 (
);
}
```
--------------------------------
### Defining setup and cleanup logic in useEffect
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/removing-effect-dependencies.md
Specify how to start and stop the Effect by connecting to a chat service and returning a disconnect cleanup function.
```javascript
const serverUrl = 'https://localhost:1234';
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => connection.disconnect();
// ...
}
```
--------------------------------
### Preconnecting in an event handler
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/preconnect.md
Call preconnect inside an event handler before initiating transitions that require resources from another host, starting connection setup as early as possible.
```javascript
import { preconnect } from 'react-dom';
function CallToAction() {
const onClick = () => {
preconnect('http://example.com');
startWizard();
}
return (
);
}
```
--------------------------------
### Install react-compiler-runtime
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-compiler/compiling-libraries.md
Installs react-compiler-runtime as a dependency to support React versions prior to version 19.
```bash
npm install react-compiler-runtime@latest
```
--------------------------------
### Write a component starter template
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/your-first-component.md
Starter sandbox template providing a placeholder to write a new custom component from scratch.
```javascript
// Write your component below!
```
--------------------------------
### Starter code for PackingList and Item components
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/conditional-rendering.md
Initial challenge setup where Item components receive name and numerical importance props without conditional rendering.
```jsx
function Item({ name, importance }) {
return (
{name}
);
}
export default function PackingList() {
return (
Sally Ride's Packing List
);
}
```
--------------------------------
### Install eslint-plugin-react-hooks
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-compiler/installation.md
Install the ESLint plugin to identify components or hooks that violate the Rules of React and cannot be optimized by the compiler.
```bash
npm install -D eslint-plugin-react-hooks@latest
```
--------------------------------
### Set up Tic-Tac-Toe game board with move history (App.js and styles.css)
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/tutorial-tic-tac-toe.md
Initial setup for the Tic-Tac-Toe application with board components, winner calculation, and history state representation.
```js
import { useState } from 'react';
function Square({ value, onSquareClick }) {
return (
);
}
function Board({ xIsNext, squares, onPlay }) {
function handleClick(i) {
if (calculateWinner(squares) || squares[i]) {
return;
}
const nextSquares = squares.slice();
if (xIsNext) {
nextSquares[i] = 'X';
} else {
nextSquares[i] = 'O';
}
onPlay(nextSquares);
}
const winner = calculateWinner(squares);
let status;
if (winner) {
status = 'Winner: ' + winner;
} else {
status = 'Next player: ' + (xIsNext ? 'X' : 'O');
}
return (
<>
>
);
}
```
--------------------------------
### preinit(href, options)
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/preinit.md
Eagerly fetches and evaluates a stylesheet or external script. Scripts execute upon download completion, and stylesheets are inserted into the document immediately.
```APIDOC
### Function: `preinit(href, options)`
#### Description
`preinit` lets you eagerly fetch and evaluate a stylesheet or external script.
#### Import
```js
import { preinit } from 'react-dom';
```
#### Parameters
- **href** (`string`) - Required. The URL of the resource you want to download and execute.
- **options** (`object`) - Required. Configuration options for preinitializing the resource:
- **as** (`string`) - Required. The type of resource. Possible values: `"script"`, `"style"`.
- **precedence** (`string`) - Required for stylesheets. Specifies where to insert the stylesheet relative to others. Possible values: `"reset"`, `"low"`, `"medium"`, `"high"`.
- **crossOrigin** (`string`) - Optional. The CORS policy to use. Possible values: `"anonymous"`, `"use-credentials"`.
- **integrity** (`string`) - Optional. A cryptographic hash of the resource to verify authenticity.
- **nonce** (`string`) - Optional. A cryptographic nonce to allow the resource when using a strict Content Security Policy.
- **fetchPriority** (`string`) - Optional. Suggests relative fetch priority. Possible values: `"auto"` (default), `"high"`, `"low"`.
#### Returns
- `void` - `preinit` returns nothing.
#### Usage Examples
##### Preiniting an external script
```js
import { preinit } from 'react-dom';
function AppRoot() {
preinit("https://example.com/script.js", {as: "script"});
return
App
;
}
```
##### Preiniting a stylesheet
```js
import { preinit } from 'react-dom';
function AppRoot() {
preinit("https://example.com/style.css", {as: "style", precedence: "medium"});
return
App
;
}
```
```
--------------------------------
### Install React type definitions with npm
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/typescript.md
Installs the latest version of type definitions for React and ReactDOM as development dependencies in an existing project.
```bash
npm install --save-dev @types/react @types/react-dom
```
--------------------------------
### Install react-devtools globally with Yarn or npm
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/react-developer-tools.md
Installs the standalone React Developer Tools package globally for browsers without extension support, such as Safari.
```bash
# Yarn
yarn global add react-devtools
# Npm
npm install -g react-devtools
```
--------------------------------
### Interactive render prop example with List, Row, and data
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/cloneElement.md
Complete implementation demonstrating the render prop alternative across App.js, List.js, Row.js, data.js, and CSS styling.
```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';
export default function List({ items, renderItem }) {
const [selectedIndex, setSelectedIndex] = useState(0);
return (
);
}
```
```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;
}
```
--------------------------------
### Create a Server Component reading from the filesystem (CounterContainer)
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/rsc/use-client.md
Does not require 'use client' because it is non-interactive and must run as a Server Component to read from the local filesystem.
```js
import { readFile } from 'node:fs/promises';
import Counter from './Counter';
export default async function CounterContainer() {
const initialValue = await readFile('/path/to/counter_value');
return
}
```
--------------------------------
### Install Parcel build tool
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/build-a-react-app-from-scratch.md
Installs Parcel as a development dependency. Parcel includes out-of-the-box support for fast refresh, JSX, TypeScript, Flow, and styling.
```bash
npm install --save-dev parcel
```
--------------------------------
### Check for duplicate React installations using npm ls react
Source: https://github.com/reactjs/react.dev/blob/main/src/content/warnings/invalid-hook-call-warning.md
Runs a dependency check in your project folder to verify whether more than one copy of the react package is installed.
```bash
npm ls react
```
--------------------------------
### Complete example of rendering a list of items using keyed Fragments
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Fragment.md
Maps over an array of post objects and assigns a key prop to each explicit Fragment container without creating unnecessary wrapper elements in the DOM.
```js
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}
);
}
```
--------------------------------
### Interactive example of reading a Promise with use inside Suspense
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/use.md
A complete example showing how to trigger and pass a Promise to a component that resolves it with the `use` API inside a Suspense boundary.
```javascript
"use client";
import { use, Suspense } from "react";
function Message({ messagePromise }) {
const messageContent = use(messagePromise);
return
Here is the message: {messageContent}
;
}
export function MessageContainer({ messagePromise }) {
return (
⌛Downloading message...}>
);
}
```
```javascript
import { useState } from "react";
import { MessageContainer } from "./message.js";
function fetchMessage() {
return new Promise((resolve) => setTimeout(resolve, 1000, "⚛️"));
}
export default function App() {
const [messagePromise, setMessagePromise] = useState(null);
const [show, setShow] = useState(false);
function download() {
setMessagePromise(fetchMessage());
setShow(true);
}
if (show) {
return ;
} else {
return ;
}
}
```
```javascript
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './styles.css';
// TODO: update this example to use
// the Codesandbox Server Component
// demo environment once it is created
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(
);
```
--------------------------------
### Interactive example of deferred list re-rendering
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/useDeferredValue.md
Complete example showing an artificially slowed list component whose re-rendering is deferred so that typing in the input remains smooth and snappy.
```js
import { useState, useDeferredValue } from 'react';
import SlowList from './SlowList.js';
export default function App() {
const [text, setText] = useState('');
const deferredText = useDeferredValue(text);
return (
<>
setText(e.target.value)} />
>
);
}
```
```js
import { memo } from 'react';
const SlowList = memo(function SlowList({ text }) {
// Log once. The actual slowdown is inside SlowItem.
console.log('[ARTIFICIALLY SLOW] Rendering 250 ');
let items = [];
for (let i = 0; i < 250; i++) {
items.push();
}
return (
{items}
);
});
function SlowItem({ text }) {
let startTime = performance.now();
while (performance.now() - startTime < 1) {
// Do nothing for 1 ms per item to emulate extremely slow code
}
return (