Introduction to React Router version 6.4
๐ Introduction to React Router v6.4+
React Router v6.4+ introduced major improvements, including **data APIs** for loading data before rendering, **actions** for submitting data, and **better routing structure**. It brings a more opinionated and full-featured approach to routing in React apps โ especially useful for creating single-page applications (SPAs).
๐ Key Features in v6.4+
- Data Loaders โ Load data before rendering a route.
- Actions โ Handle form submissions and mutations.
- Error Boundaries โ Route-level error handling.
- Nested Routes + Layouts โ Powerful layout support.
- createBrowserRouter โ A new setup approach.
๐ฆ Installation
npm install react-router-dom@6
๐ ๏ธ Basic Setup with Data Loader
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: ,
loader: async () => {
const data = await fetch("/api/home");
return data.json();
},
errorElement:
},
]);
function App() {
return ;
}
๐ค Handling Forms with Actions
{
path: "/contact",
element: ,
action: async ({ request }) => {
const formData = await request.formData();
// Process and send to backend
}
}
๐ง Why v6.4+ is Better:
- No need for useEffect to load data โ use Loaders instead.
- Submit forms declaratively with
- Error handling is more robust and isolated.
๐ Example Directory Structure:
src/
โ
โโโ routes/
โ โโโ Home.jsx
โ โโโ ContactForm.jsx
โ โโโ ErrorPage.jsx
โ
โโโ App.jsx
โโโ main.jsx
โ
Conclusion
React Router 6.4+ modernizes routing with data and layout capabilities that rival frameworks like Next.js and Remix โ while staying in the React ecosystem.