### Full createRoot app example with public/index.html, src/index.js, and src/App.js
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/client/createRoot.md
Sandpack example showing the HTML DOM node, the entry file that creates the root and renders App, and the App component with a Counter. Use this as a complete setup for an app fully built with React.
```html
My app
```
```js
import { createRoot } from 'react-dom/client';
import App from './App.js';
import './styles.css';
const root = createRoot(document.getElementById('root'));
root.render();
```
```js
import { useState } from 'react';
export default function App() {
return (
<>
Hello, world!
>
);
}
function Counter() {
const [count, setCount] = useState(0);
return (
);
}
```
--------------------------------
### 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; }
```
--------------------------------
### package.json for Suspense examples
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
Dependencies for the interactive examples.
```json
{
"dependencies": {
"react": "19.3.0",
"react-dom": "19.3.0",
"react-scripts": "latest"
}
}
```
--------------------------------
### 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; }
```
--------------------------------
### 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();
// ...
}
```
--------------------------------
### 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'},
];
```
--------------------------------
### Install react-devtools-cdt-mcp
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/dev-tools/react-devtools-cdt-mcp.md
Install the react-devtools-cdt-mcp package as a development dependency using npm.
```bash
npm install --save-dev react-devtools-cdt-mcp
```
--------------------------------
### 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
```
--------------------------------
### 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(
);
```
--------------------------------
### Suspense with nested components example
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
Example showing Biography and Albums fetching data under a single Suspense boundary, so they pop in together. Includes App, ArtistPage, Panel, Biography, Albums, and data fetching logic.
```jsx
import { useState } from 'react';
import ArtistPage from './ArtistPage.js';
export default function App() {
const [show, setShow] = useState(false);
if (show) {
return (
);
} else {
return (
);
}
}
```
```jsx
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...
;
}
```
```jsx
export default function Panel({ children }) {
return (
{children}
);
}
```
```jsx
import {use} from 'react';
import { fetchData } from './data.js';
export default function Biography({ artistId }) {
const bio = use(fetchData(`/${artistId}/bio`));
return (
{bio}
);
}
```
```jsx
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;
}
```
--------------------------------
### 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 (
Text: {text}
)
}
export default SlowList;
```
```css
.items {
padding: 0;
max-height: 300px;
overflow: auto;
}
.item {
list-style: none;
display: block;
height: 40px;
padding: 5px;
margin-top: 10px;
border-radius: 4px;
border: 1px solid #aaa;
}
```
--------------------------------
### 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
```
--------------------------------
### Calling preinit from react-dom
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/preinit.md
Provide a hint to the browser to start downloading and executing a resource during component execution.
```javascript
import { preinit } from 'react-dom';
function AppRoot() {
preinit("https://example.com/script.js", {as: "script"});
// ...
}
```
--------------------------------
### Suspense with data fetching using use (Albums example)
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
This example shows a Suspense boundary wrapping an Albums component that suspends while fetching data with use. The fallback is shown until the data loads.
```jsx
import { useState } from 'react';
import ArtistPage from './ArtistPage.js';
export default function App() {
const [show, setShow] = useState(false);
if (show) {
return (
);
} else {
return (
);
}
}
```
```jsx
import { Suspense } from 'react';
import Albums from './Albums.js';
export default function ArtistPage({ artist }) {
return (
<>
{artist.name}
}>
>
);
}
function Loading() {
return
🌀 Loading...
;
}
```
```jsx
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 {
throw Error('Not implemented');
}
}
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 styles
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
CSS styles used in the example.
```css
main {
min-height: 200px;
padding: 10px;
}
.layout {
border: 1px solid black;
}
.header {
background: #222;
padding: 10px;
text-align: center;
color: white;
}
.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;
}
```
--------------------------------
### Data fetching utility for Suspense example
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
This module provides a cached fetchData function used by the Suspense examples. It simulates a data fetching layer with a fake delay and returns search results for album queries. The caching logic is typically handled by a framework in real applications.
```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.startsWith('/search?q=')) {
return await getSearchResults(url.slice('/search?q='.length));
} else {
throw Error('Not implemented');
}
}
async function getSearchResults(query) {
// Add a fake delay to make waiting noticeable.
await new Promise(resolve => {
setTimeout(resolve, 500);
});
const allAlbums = [{
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
}];
const lowerQuery = query.trim().toLowerCase();
return allAlbums.filter(album => {
const lowerTitle = album.title.toLowerCase();
return (
lowerTitle.startsWith(lowerQuery) ||
lowerTitle.indexOf(' ' + lowerQuery) !== -1
)
});
}
```
--------------------------------
### Example Component Stack trace output
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/captureOwnerStack.md
Shows the full hierarchy of component and DOM elements surrounding an error thrown by SubComponent.
```text
at SubComponent
at fieldset
at Component
at main
at React.Suspense
at App
```
--------------------------------
### Migrating a simple component to a function component
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Component.md
Complete example of rendering the Greeting function component with destructured props inside App.
```js
function Greeting({ name }) {
return
Hello, {name}!
;
}
export default function App() {
return (
<>
>
);
}
```
--------------------------------
### 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 (
);
}
```
--------------------------------
### Solution: useInterval implementation and integration
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/reusing-logic-with-custom-hooks.md
Implements `useInterval` with `useEffect` to manage interval setup and cleanup, and updates `useCounter` to use it.
```javascript
import { useCounter } from './useCounter.js';
export default function Counter() {
const count = useCounter(1000);
return
Seconds passed: {count}
;
}
```
```javascript
import { useState } from 'react';
import { useInterval } from './useInterval.js';
export function useCounter(delay) {
const [count, setCount] = useState(0);
useInterval(() => {
setCount(c => c + 1);
}, delay);
return count;
}
```
```javascript
import { useEffect } from 'react';
export function useInterval(onTick, delay) {
useEffect(() => {
const id = setInterval(onTick, delay);
return () => clearInterval(id);
}, [onTick, delay]);
}
```
--------------------------------
### Indicating a Transition with useTransition
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
This example shows how to use useTransition to get an isPending boolean and pass it to a Layout component to visually indicate a pending transition. It includes a Suspense fallback for loading.
```jsx
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
);
}
```
```jsx
export default function IndexPage({ navigate }) {
return (
);
}
```
```jsx
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 (
);
}
```
```jsx
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})
))}
);
}
```
```jsx
import {use} from 'react';
import { fetchData } from './data.js';
export default function Biography({ artistId }) {
const bio = use(fetchData(`/${artistId}/bio`));
return (
{bio}
);
}
```
```jsx
export default function Panel({ children }) {
return (
{children}
);
}
```
--------------------------------
### 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!
```
--------------------------------
### VideoPlayer with missing dependency causing lint error
Source: https://github.com/reactjs/react.dev/blob/main/src/content/learn/synchronizing-with-effects.md
The Effect uses the isPlaying prop but the dependency array is empty, triggering the error "React Hook useEffect has a missing dependency: 'isPlaying'". This example shows the incorrect setup before fixing the dependency array.
```jsx
import { useState, useRef, useEffect } from 'react';
function VideoPlayer({ src, isPlaying }) {
const ref = useRef(null);
useEffect(() => {
if (isPlaying) {
console.log('Calling video.play()');
ref.current.play();
} else {
console.log('Calling video.pause()');
ref.current.pause();
}
}, []); // This causes an error
return ;
}
export default function App() {
const [isPlaying, setIsPlaying] = useState(false);
const [text, setText] = useState('');
return (
<>
setText(e.target.value)} />
>
);
}
```
```css
input, button { display: block; margin-bottom: 20px; }
video { width: 250px; }
```
--------------------------------
### Waiting for an image to load with ViewTransition
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/Suspense.md
Inside a ViewTransition, React waits up to 500 ms for visible images to load before starting the animation. Setting loading="lazy" or adding an onLoad handler opts an image out. This example compares the same Suspense boundary inside and outside a ViewTransition.
```js
import {
ViewTransition,
Suspense,
use,
useState,
} from 'react';
import { fetchImageSrc } from './image.js';
function Profile({ cacheKey }) {
const src = use(fetchImageSrc(cacheKey));
return (
Jack Pope
);
}
function ProfilePlaceholder() {
return (
);
}
export default function App() {
const [showWithTransition, setShowWithTransition] =
useState(false);
const [showWithoutTransition, setShowWithoutTransition] =
useState(false);
return (
<>
{showWithTransition && (
}>
)}
{showWithoutTransition && (
}>
)}
>
);
}
```
```js
// Normally, the caching logic would be inside a framework.
const cache = new Map();
export function fetchImageSrc(cacheKey) {
if (!cache.has(cacheKey)) {
cache.set(cacheKey, loadImageSrc());
}
return cache.get(cacheKey);
}
async function loadImageSrc() {
// Delay the response so the Suspense fallback is visible.
await new Promise(resolve => setTimeout(resolve, 1000));
// Add a unique parameter so the image isn't cached.
return 'https://react.dev/images/team/jack-pope.jpg?t=' + Date.now();
}
```
```css
#root {
min-height: 390px;
}
.card {
margin-top: 1em;
}
.card img {
display: block;
border-radius: 50%;
background: #dfe3e9;
}
.card p {
font-weight: bold;
}
.avatar-placeholder {
width: 80px;
height: 80px;
border-radius: 50%;
background: #dfe3e9;
}
.name-placeholder {
width: 90px;
border-radius: 4px;
background: #dfe3e9;
}
hr {
margin: 16px 0;
}
```
```json
{
"dependencies": {
"react": "19.3.0",
"react-dom": "19.3.0",
"react-scripts": "latest"
}
}
```
--------------------------------
### 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
);
}
```
--------------------------------
### Implement custom error reporting with onCaughtError, onUncaughtError, and onRecoverableError
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react-dom/client/hydrateRoot.md
This example shows a complete setup for custom error reporting. The reportError.js file defines handlers for caught, uncaught, and recoverable errors, which are then passed to hydrateRoot in index.js. The App.js component triggers errors for demonstration.
```javascript
function reportError({ type, error, errorInfo }) {
// The specific implementation is up to you.
// `console.error()` is only used for demonstration purposes.
console.error(type, error, "Component Stack: ");
console.error("Component Stack: ", errorInfo.componentStack);
}
export function onCaughtErrorProd(error, errorInfo) {
if (error.message !== "Known error") {
reportError({ type: "Caught", error, errorInfo });
}
}
export function onUncaughtErrorProd(error, errorInfo) {
reportError({ type: "Uncaught", error, errorInfo });
}
export function onRecoverableErrorProd(error, errorInfo) {
reportError({ type: "Recoverable", error, errorInfo });
}
```
```javascript
import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
import {
onCaughtErrorProd,
onRecoverableErrorProd,
onUncaughtErrorProd,
} from "./reportError";
const container = document.getElementById("root");
hydrateRoot(container, , {
// Keep in mind to remove these options in development to leverage
// React's default handlers or implement your own overlay for development.
// The handlers are only specified unconditionally here for demonstration purposes.
onCaughtError: onCaughtErrorProd,
onRecoverableError: onRecoverableErrorProd,
onUncaughtError: onUncaughtErrorProd,
});
```
```javascript
import { Component, useState } from "react";
function Boom() {
foo.bar = "baz";
}
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return
```
--------------------------------
### Custom useIntersectionObserver Hook Example
Source: https://github.com/reactjs/react.dev/blob/main/src/content/reference/react/useEffect.md
This example is identical to an earlier example but extracts the intersection observer logic into a custom Hook. It includes App.js, Box.js, and useIntersectionObserver.js.
```js
import Box from './Box.js';
export default function App() {
return (
<>
>
);
}
function LongSection() {
const items = [];
for (let i = 0; i < 50; i++) {
items.push(
Item #{i} (keep scrolling)
);
}
return
{items}
}
```
```js
import { useRef, useEffect } from 'react';
import { useIntersectionObserver } from './useIntersectionObserver.js';
export default function Box() {
const ref = useRef(null);
const isIntersecting = useIntersectionObserver(ref);
useEffect(() => {
if (isIntersecting) {
document.body.style.backgroundColor = 'black';
document.body.style.color = 'white';
} else {
document.body.style.backgroundColor = 'white';
document.body.style.color = 'black';
}
}, [isIntersecting]);
return (
);
}
```
```js
import { useState, useEffect } from 'react';
export function useIntersectionObserver(ref) {
const [isIntersecting, setIsIntersecting] = useState(false);
useEffect(() => {
const div = ref.current;
const observer = new IntersectionObserver(entries => {
const entry = entries[0];
setIsIntersecting(entry.isIntersecting);
}, {
threshold: 1.0
});
observer.observe(div);
return () => {
observer.disconnect();
}
}, [ref]);
return isIntersecting;
}
```
--------------------------------
### 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
```
--------------------------------
### 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; }
```
--------------------------------
### 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
```