Client-Side Hydration with Bun and React
Bun makes it easy to implement client-side hydration when using server-side rendering (SSR) with React. Here's how it works:
1. Server-Side Rendering
On the server, you render your React components to an HTML stream using `renderToReadableStream` from `react-dom/server`. This generates the initial HTML that will be sent to the client.
jsx
import { renderToReadableStream } from "react-dom/server";
const stream = await renderToReadableStream(
<App initialData={data} />,
{
bootstrapScripts: ["/public/index.js"],
}
);
The `bootstrapScripts` option specifies the path to the client-side JavaScript bundle that will hydrate the React application on the client.
2. Bundling Client-Side Code
Bun's built-in bundler is used to create the client-side JavaScript bundle. You can configure this in your `index.ts` file:
js
await Bun.build({
entrypoints: ["./src/react/index.tsx"],
outdir: "./public",
});
This will bundle your React code and output it to the `./public/index.js` file.
3. Client-Side Hydration
On the client, Bun will automatically load the `index.js` bundle and hydrate the React application. The `ReactDOM.hydrateRoot` function is used to hydrate the pre-rendered HTML with the client-side React application.
jsx
// src/react/index.tsx
import { hydrateRoot } from "react-dom/client";
hydrateRoot(document.getElementById("root"), <App />);
The hydration process attaches event handlers and other interactivity to the pre-rendered HTML, allowing the application to function fully on the client.
Helpful Resources
- Bun's documentation on server-side rendering React- Example repository demonstrating Bun SSR with React- Video tutorial on building a React SSR app with Bun
In summary, Bun streamlines the process of server-side rendering React components and client-side hydration. By using Bun's built-in bundler and the `renderToReadableStream` and `hydrateRoot` functions from `react-dom`, you can efficiently implement a full-stack React application with server-side rendering and client-side interactivity[1][3][4].
Citations:[1] https://www.alexkates.dev/blog/server-side-rendering-ssr-with-bun-and-react
[2] https://asleepace.com/blog/bun-elysia-react-ssr/
[3] https://bun.sh
[4] https://www.youtube.com/watch?v=uUBAI_FGbaE
[5] https://github.com/alexkates/ssr-bun-react
[6] https://github.com/asleepace/bun-elysia-react-srr-example
[7] https://bun.sh/guides/ecosystem/ssr-react
[8] https://www.reddit.com/r/react/comments/16icmis/react_ssr_with_bun_elysia/