Command Palette

Search for a command to run...

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

use(Context) after an early return and inside an if

Changing the context re-renders every component that read it with use, the same as useContext. The hidden badge and the gray notice never read it.

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?

use(Context) after an early return and inside an if

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

New (light) | Notice in red | Notice in gray
New (dark) | Notice in orange | Notice in gray