React Router v6 – useLoaderData in server-side rendered application

  Kiến thức lập trình

I have a server-side rendered app organized in very much the same way as follows:


export default function App() {
    return (
          <title>Server Rendered App</title>
            <Route path="/" element={<div>Home</div>} />
            <Route path="/about" element={<div>About</div>} />
          <script src="/build/client.ts" />


import express from "express";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "./App";

let app = express();

app.get("*", (req, res) => {
    let html = ReactDOMServer.renderToString(
      <StaticRouter location={req.url}>
        <App />
    res.send("<!DOCTYPE html>" + html);


import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";

      <App />

Now, I want to be able to use the loader pattern and the useLoaderData hook provided by react-router in order to fetch data and make it available to the underlying component – in other words, to be able to pass data from server-side route fetching to the component.

However, all of the tutorials and examples that I see use createBrowserRouter but I’m not sure how to go about integrating that with my existing application.

Is there a way to directly use the loader pattern and useLoaderData in my application as it currently stands or can anyone instruct me on how to go about migrating my SSR app to support something like createBrowserRouter?