use is a React API that lets you read a resource during rendering, such as a Promise or context.
const value = use(resource);The
use APIWhy use Was Added
Before React 19, reading asynchronous data or consuming context had rigid limitations:
- Strict Rules of Hooks: Traditional React Hooks like
useContextoruseEffectmust be called unconditionally at the top level of a component. You could not place them insideifstatements, loops, or early returns. - Complex Data Fetching in Client Components: Handling async data fetching on the client typically required cumbersome boilerplate using
useEffectand multiple state variables (data,isLoading,error), which often led to race conditions and waterfall requests. - Server-to-Client Data Streaming: With React Server Components (RSC), there was no standard mechanism to pass an in-flight server promise to a Client Component and suspend rendering until the data resolved.
use solves these issues by providing a flexible API that integrates directly with React's Suspense and Error Boundary systems.What use Does
use allows a component to synchronously read the value of a resource—specifically Promises or Context—directly during rendering.- Flexibility: Unlike standard hooks,
usecan be called conditionally insideifstatements,forloops, or after early returns. - Unwraps Promises: When passed a Promise,
usesuspends rendering until the Promise resolves, then returns its resolved value. If the Promise rejects, it triggers the nearest Error Boundary. - Consumes Context: When passed a React Context, it retrieves the context value just like
useContext, but with the ability to be called conditionally.
How use Works
While
use behaves similarly to a Hook, use is an API, not a Hook. This difference is key to how React handles it under the hood:1. Consuming Promises (use(promise))
When React renders a component calling
use(promise):- Pending: If the Promise is still pending,
usethrows a special internal signal (or "suspense exception") that pauses rendering for that subtree and displays the nearest `` fallback UI. - Fulfilled: Once the Promise resolves, React retries rendering the component.
usereads the resolved value synchronously and returns it. - Rejected: If the Promise fails,
usethrows the rejection reason, delegating error handling to the nearest ``.
Important Rule: Promises passed tousemust be cached (e.g., via a framework loader, a Server Component prop, or a cache layer like React'scache). Creating a new Promise directly inside the render body will cause React to recreate the Promise on every render and loop endlessly on the Suspense fallback.
import { use, Suspense } from 'react';
// Client component unwraps a cached Promise passed from a server component or cache layer
function UserProfile({ userPromise }) {
const user = use(userPromise); // Suspends until userPromise resolves
return {user.name};
}export default function App({ userPromise }) {
return ( Loading profile...
}>);
}
#### 2. Consuming Context (`use(context)`)
When passed a React Context, `use` searches up the component tree to locate the closest context provider for that context and returns its current value.
```jsx
import { use } from 'react';
function Navigation({ isLoggedIn }) {
// Conditionally read context based on runtime state
if (isLoggedIn) {
const userTheme = use(UserThemeContext);
return ;
}
return ;
}
No comments:
Post a Comment