In this series, I am going to share what I found about React Router!!!
What is React Router?
React Router is a router for React. Many see it as a simple router for React apps, but I see it as a powerful tool for managing a well-furnished Single Page Application(SPA).
What I will acknowledge throughout the series:-
- Different modes provided by React Router.
- How declarative mode was lagging.
- How Data mode introduced in v6 changed everything.
- How Data mode introduced in v6 changed everything.
- All utilities and integration.
The features available in each mode are additive, so moving from Declarative to Data to Framework adds more features at the cost of architectural control.
Declarative Mode
Declarative mode enables basic routing features like matching URLs to components, navigating around the app, and providing active states with APIs like <Link>, useNavigate, and useLocation.
import { BrowserRouter } from "react-router";
ReactDOM.createRoot(root).render(
<BrowserRouter>
<App />
</BrowserRouter>,
);
Data Mode
By moving route configuration outside of React rendering, Data Mode adds data loading, actions, pending states, and more with APIs like loader, action, and useFetcher.
import {
createBrowserRouter,
RouterProvider,
} from "react-router";
let router = createBrowserRouter([
{
path: "/",
Component: Root,
loader: loadRootData,
},
]);
ReactDOM.createRoot(root).render(
<RouterProvider router={router} />,
);
Framework Mode
Framework Mode wraps Data Mode with a Vite plugin to add the full React Router experience with:
- type-safe href
- type-safe Route Module API
- intelligent code splitting
- SPA, SSR, and static rendering strategies and more
import { index, route } from "@react-router/dev/routes";
export default [
index("./home.tsx"),
route("products/:pid", "./product.tsx"),
];
You'll then have access to the Route Module API with type-safe params, loaderData, code splitting, SPA/SSR/SSG strategies, and more.
import { Route } from "./+types/product.tsx";
export async function loader({ params }: Route.LoaderArgs) {
let product = await getProduct(params.pid);
return { product };
}
export default function Product({
loaderData,
}: Route.ComponentProps) {
return <div>{loaderData.product.name}</div>;
}
One can choose:-
- Declarative mode for simple apps with much less overhead.
- Data mode for more hands-on control, like parallel data loading and rendering.
- Finally, Framework Mode gives us the most out of it with the framework-level integration with
vitefor easy migration toNext.js, but it's not our concern for now.
In this series, our main focus is Data Mode, and we'll dive deep into it.
References & Credits
- React Router Documentation – Core concepts and API definitions
- Kevin Julián Martínez Escobar – Inspiration for this article
Top comments (0)