Hello, fellow React enthusiasts! The React ecosystem never stops evolving, and the latest update brings an exciting new feature: you can now pass Promises directly from Server Components to Client Components. This means you can take advantage of data streaming and asynchronous rendering like never before!
What Does This Mean?
In a nutshell, instead of waiting on the server to await
data and then passing it as props, you can now generate a Promise on the server and pass it directly to the client. The client then uses React’s new use
hook to resolve that Promise. This approach opens up possibilities for avoiding render-blocking and keeping your code more concise.
How It Works in Code
Server Component: src/App.js
On the server side, we fetch data asynchronously and generate a Promise. We then pass that Promise as a prop to a Client Component. Check out the code below:
import { Suspense } from "react";
import { fetchMessage } from "./lib.js";
import { Message } from "./Message.js";
export default function App() {
// Asynchronously fetch data on the server, which returns a Promise
const messagePromise = fetchMessage();
return (
<Suspense fallback={<p>Loading message...</p>}>
{/* Pass the Promise directly to the Message component */}
<Message messagePromise={messagePromise} />
</Suspense>
);
}
Client Component: src/Message.js
On the client side, we use the new use
hook to resolve the Promise passed from the server and render the content:
"use client";
import { use } from "react";
export function Message({ messagePromise }) {
// Wait for the Promise to resolve and get the message content
const messageContent = use(messagePromise);
return <p>Message: {messageContent}</p>;
}
Benefits of This New Approach
Seamless Data Streaming:
Creating a Promise on the server and resolving it on the client prevents the server from blocking the client’s render process. This can lead to smoother and more efficient data streaming.Cleaner Code:
Compared to traditional data fetching—where you’d await data on the server and pass it as props—this method offers a cleaner, more straightforward pattern for managing asynchronous data between Server and Client Components.Flexibility:
The newuse
hook can be used anywhere inside a React component or custom hook (including loops and conditional statements), as long as it’s invoked within a component’s body.
A Few Caveats
- The
use
hook is only available within React components or custom hooks. - The value resolved from the Promise must be serializable. Non-serializable values (like functions) cannot be passed this way.
In Summary
With the introduction of the use
API in React 19, you can now pass Promises directly from server to client, making your data fetching patterns simpler and more efficient. Whether you’re chasing better performance or just cleaner code, this feature is a game changer for modern React applications.
For more details, be sure to check out the official React documentation.
Happy coding!
Top comments (0)