In this article, we will explore how to consume an API using the new use API in React 19, a feature that simplifies the management of asynchronous data in applications.
I’m also sharing the step-by-step process in a video. Don’t forget to subscribe to my channel ❤️.
First the comple code:
import {use, Suspense } from 'react';
const fetchUsers = async () => {
const res = await
fetch('https://jsonplaceholder.typicode.com/users');
return res.json();
};
const userPromise = fetchUsers();
const Users = () => {
const users = use(userPromise);
return (
<ul>
{users.map((user) => (
<div key={user.id}>
<h2>{user.name}</h2>
</div>
))}
</ul>
);
};
function App() {
return (
<Suspense fallback={<h1>Loading...</h1>}>
<Users />
</Suspense>
);
}
export default App;
And now...
The Scenario
Let’s suppose you have an application where you need to consume an API (for example, an API to fetch usernames). Previously, you would have used useEffect, but with React 19, things are different. Now, you can use the use API, which allows handling promises in a much simpler way.
Breaking Down the Code
- fetchUsers and userPromise
First, the fetchUsers function is defined to fetch data from an API, and the promise is stored in userPromise.
const fetchUsers = async () => {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
return res.json();
};
const userPromise = fetchUsers();
- The Users Component
Then, in the Users component, the use API is used to handle the promise:
const Users = () => {
const users = use(userPromise);
return (
<ul>
{users.map((user) => (
<div key={user.id}>
<h2>{user.name}</h2>
</div>
))}
</ul>
);
};
- Suspense in Action
Finally, the Users component is wrapped in a Suspense component, which displays a "Loading..." message while the promise is being resolved.
function App() {
return (
<Suspense fallback={<h1>Loading...</h1>}>
<Users />
</Suspense>
);
}
Considerations
It’s important to note that use doesn’t support promises created during the render phase, so they must be created outside of this phase, as was done with userPromise. Although, in the React blog, they mention that they will bring solutions for this in the future.
Conclusion
React 19 introduces powerful tools to simplify application development. The use API is one of them, making asynchronous data management more intuitive and efficient.
Thank you very much!
Best regards,
Pablo.
Top comments (0)