Topic 51 of 54
Resolving Promises
Overview
React 19 introduces a revolutionary new API simply called `use`. It allows you to read the value of a Promise (or a Context) directly during the render phase, pausing the render until the Promise resolves. It effectively replaces the need for `useEffect` data fetching in many client-side scenarios and natively integrates with `<Suspense>`.
Syntax
`use` is unique. Unlike normal hooks, it CAN be called conditionally (inside an if-statement or loop). When it hits an unresolved promise, it throws it up to the nearest `<Suspense>` boundary.
Reading a Promise with 'use'
jsx
import { use, Suspense } from 'react';
// A mock fetch function returning a promise
const fetchMessage = fetch('/api/message').then(res => res.json());
function MessageDisplay({ messagePromise }) {
// 'use' pauses rendering until the promise resolves!
// No useState, no useEffect, no loading flags!
const message = use(messagePromise);
return <p>{message.text}</p>;
}
export default function App() {
return (
// Suspense catches the pause and shows the fallback
<Suspense fallback={<p>Loading message...</p>}>
<MessageDisplay messagePromise={fetchMessage} />
</Suspense>
);
}Common Pitfalls
- Calling `use` on a promise created *inside* the render body. This will create a new promise every render, causing an infinite Suspense loop. The promise must be passed in as a prop or created outside the component.
Interview Tips
- The `use` API is a massive paradigm shift in React 19. Knowing how it interacts with `<Suspense>` demonstrates cutting-edge knowledge of the ecosystem.
Real-World Example
Using `use` to conditionally read Context, which `useContext` historically could not do.
example
jsx
function Header({ showTheme }) {
// You couldn't do this with useContext!
if (showTheme) {
const theme = use(ThemeContext);
return <p>Current theme: {theme}</p>;
}
return <p>Header</p>;
}