Home > Web Front-end > JS Tutorial > React New API use(promise)

React New API use(promise)

DDD
Release: 2025-01-14 06:39:42
Original
395 people have browsed it

In this post, I’ll demo how to read a value from a promise using use.

Links

  • Demo

  • Codebase

Snippet

Let’s check out the following code:

import { Suspense } from "react";

export default function Page() {
  const messagePromise = fetchMessages();

  return (
    <Suspense fallback={<p>⌛ waiting for messages...</p>}>
      <Message messagePromise={messagePromise} />
    </Suspense>
  );
}
Copy after login

A couple of things to note:

  • is being used, which basically displays the fallback, in this case: ⌛ waiting for messages..., until the promise is resolved.

  • messagePromise is a promise passed as a prop to .

Now, let’s take a look at fetchMessages:

async function fetchMessages() {
  return [
    {
      id: 1,
      text: "message 1",
    },
    {
      id: 2,
      text: "message 2",
    },
  ];
}
Copy after login

As you can see, it’s a very simple function. In a real world example, this could be a fetch request, but for simplicity, the function just returns an array. By using async, JavaScript automatically knows that the function returns a promise.

Finally, let’s check out the component:

function Message({ messagePromise }) {
  const comments = use(messagePromise);

  return comments.map((comment) => <p key={comment.id}>{comment.text}</p>);
}
Copy after login

This is where it gets interesting. The component receives messagePromise as a prop, which, as we mentioned, is a promise.

Usually, you’d use await with a promise, but in React 19, you can now use use to achieve basically the same result.

One key difference between await and use is that await blocks rendering until the promise is resolved, whereas use doesn’t block rendering.

Here’s how the component looks before the promise is resolved:

React  New API use(promise)

And once the promise is resolved:

React  New API use(promise)

Conclusion

use works similarly to await, and if the application is running on a server using SSR, the result is exactly the same: the server will return the same HTML response in both cases.

However, if the code runs on the client, rendering behaves a bit differently. await blocks rendering until the promise is resolved, while use allows the component to re-render once the promise is resolved.

The above is the detailed content of React New API use(promise). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template