React HooksEasy
What is the new `use` API in React 19?
The use API is a revolutionary new feature in React 19 that allows you to read the value of a resource—like a Promise or Context—directly inside the render function of a component or a custom hook.
Key Capabilities:
- First-Class Promises: You can pass a Promise directly to
use(promise). React will suspend the component until the Promise resolves. This eliminates the need to manually trackloadingstate or useuseEffectfor data fetching. - Conditional Context: Unlike
useContext, which must be called at the top level of a component,use(Context)can be called conditionally (e.g., inside anifstatement or a loop). - Integration with Suspense: When a component is suspended via
use, React climbs the tree to find the nearest<Suspense>boundary and displays its fallback UI.
Code example
tsx
1import React, { use, Suspense } from 'react';23// A mock asynchronous data fetcher4const fetchUser = async (id) => {5 const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);6 return res.json();7};89// We create the promise outside or pass it in as a prop10const userPromise = fetchUser(1);1112function UserProfile({ promise }) {13 // 🚀 The Magic of 'use'!14 // The component completely halts here until the promise resolves.15 // No need for useState or useEffect for data fetching.16 const user = use(promise);1718 return (19 <div className="p-6 bg-white border rounded-2xl shadow-lg">20 <h2 className="text-2xl font-bold">{user.name}</h2>21 <p className="text-gray-600">{user.email}</p>22 </div>23 );24}2526export default function App() {27 return (28 <div className="p-8">29 <h1 className="text-3xl font-extrabold mb-6">React 19 'use' API</h1>3031 {/* Suspense catches the promise and displays the fallback */}32 <Suspense fallback={<div className="text-blue-500 font-bold animate-pulse">Loading User Data...</div>}>33 <UserProfile promise={userPromise} />34 </Suspense>35 </div>36 );37}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React Hooks set.