Skip to content

Development Tips 💭

Jonathan Chue edited this page Jun 21, 2024 · 1 revision

React Router

The original way to set up routing (that's still showed in some examples) was to add Route components inside the root App component:

/* App.tsx */

import { Routes, Route, Outlet, Link } from "react-router-dom";

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<Root />}>
        <Route path="projects" element={<ProjectsList />}>
          <Route path=":projectId" element={<ProjectPage />} />
        </Route>
      </Route>
    </Routes>
  );
}

function Root() {
  return (
    <div>
      <nav>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/projects">Projects</Link>
          </li>
        </ul>
      </nav>

      <Outlet />
    </div>
  );
}

But this causes a waterfalling render+fetch chain that increases loading time, especially when each component fetches some data.

The better approach is to create the router outside of the React component tree by defining it in the main file using the createBrowserRouter function and the RouterProvider element:

/* main.tsx */

import * as React from "react";
import * as ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import "./index.css";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Root />,
    children: [
      {
        path: "projects",
        element: <Projects />,
        children: [
          {
            path: ":projectId",
            element: <ProjectPage />,
          },
        ],
      },
    ],
  },
]);

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

This solution allows data to be fetched in parallel, eliminating slow render+fetch chains. The good news is that this is the method shown in the official tutorial.

You can read more in this blog post.

Maps

Ways to optimize and speed up web maps:

Clone this wiki locally