Como consumir una API con REACT 19 | use - suspense

Pablo on the code - Sep 16 - - Dev Community

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.

First, I would like to share the video for this article. For now, it is in Spanish, but it might be useful to accompany this article in English. Anyway, I am planning to create a channel in English very soon 😁

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();
Enter fullscreen mode Exit fullscreen mode
  • 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>
  );
};
Enter fullscreen mode Exit fullscreen mode
  • 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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.

.
Terabox Video Player