Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 14.4 — use(): Reading Promises and Context
React · Example 2 of 3

A rejected promise goes to the error boundary

Pending: the Suspense fallback. Rejected: the error boundary's message. React also logs the caught error (the middle lines) in development.

use(resource) reads the value of a promise (suspending until it settles) or of a context; unlike other hooks it may be called inside if blocks and after early returns, but the promise must be created outside render or cached, never made fresh on every render.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a getProduct(id) cache and a Product component that reads it with use, inside a Suspense boundary with a fallback.

02

Write a Greeting component that only reads UserContext (with use) when the prop personal is true, and says Hello! otherwise.

03

A parent should load comments when a button is clicked and pass them to Comments, which reads them with use. Write both, keeping the button page visible while loading.

Explain it without notes

01

What does use(promise) do for each state of the promise?

02

Why can use be called conditionally when useState and useContext cannot?

03

Why must a promise passed to use be cached or created outside render? What happens otherwise?

04

How do Suspense and error boundaries divide the work when you read data with use?

A rejected promise goes to the error boundary

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

screen: Loading orders...
Error: Server returned 500

The above error occurred in the <Orders> component.

React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.

screen: Could not load: Server returned 500