React Router 6 Basics
createBrowserRouter
createBrowserRouter creates a router that uses the HTML5 History API to manage browser navigation, including forward and backward buttons. It is the most recommended router type for modern browsers.
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import RootLayout from "./layouts/RootLayout";
import Home from "./pages/Home";
import About from "./pages/About";
const router = createBrowserRouter([
{
path: "/",
element: <RootLayout />,
children: [
{
index: true,
element: <Home />,
},
{
path: "about",
element: <About />,
},
],
},
]);
function App() {
return <RouterProvider router={router} />;
}Type Declaration
function createBrowserRouter(
routes: RouteObject[],
opts?: {
basename?: string;
future?: FutureConfig;
hydrationData?: HydrationState;
window?: Window;
}
): RemixRouter;createHashRouter
createHashRouter creates a router that uses the URL’s hash fragment (#) for navigation. It is useful in environments that do not support the HTML5 History API, such as older browsers or iframes.
import { createHashRouter, RouterProvider } from "react-router-dom";
import RootLayout from "./layouts/RootLayout";
import Home from "./pages/Home";
import About from "./pages/About";
const router = createHashRouter([
{
path: "/",
element: <RootLayout />,
children: [
{
index: true,
element: <Home />,
},
{
path: "about",
element: <About />,
},
],
},
]);
function App() {
return <RouterProvider router={router} />;
}createMemoryRouter
createMemoryRouter creates a router that operates in memory, ideal for testing and non-browser environments like server-side rendering. It does not rely on the browser’s History API or URL but simulates navigation using an in-memory state. It is commonly used in tools like Storybook or for running React Router in non-browser contexts.
import {
RouterProvider,
createMemoryRouter,
} from "react-router-dom";
import * as React from "react";
import {
render,
waitFor,
screen,
} from "@testing-library/react";
import "@testing-library/jest-dom";
import CalendarEvent from "./routes/event";
test("event route", async () => {
const FAKE_EVENT = { name: "test event" };
const routes = [
{
path: "/events/:id",
element: <CalendarEvent />,
loader: () => FAKE_EVENT,
},
];
const router = createMemoryRouter(routes, {
initialEntries: ["/", "/events/123"],
initialIndex: 1,
});
render(<RouterProvider router={router} />);
await waitFor(() => screen.getByRole("heading"));
expect(screen.getByRole("heading")).toHaveTextContent(
FAKE_EVENT.name
);
});Type Declaration
function createMemoryRouter(
routes: RouteObject[],
opts?: {
basename?: string;
future?: FutureConfig;
hydrationData?: HydrationState;
initialEntries?: InitialEntry[];
initialIndex?: number;
}
): RemixRouter;createStaticHandler
createStaticHandler creates a static route handler for pre-rendering or static site generation. It is used in conjunction with createStaticRouter rather than directly building a router.
import {
createStaticHandler,
createStaticRouter,
StaticRouterProvider,
} from "react-router-dom/server";
import Root, {
loader as rootLoader,
ErrorBoundary as RootBoundary,
} from "./root";
const routes = [
{
path: "/",
loader: rootLoader,
Component: Root,
ErrorBoundary: RootBoundary,
},
];
export async function renderHtml(req) {
let { query, dataRoutes } = createStaticHandler(routes);
let fetchRequest = createFetchRequest(req);
let context = await query(fetchRequest);
// If we got a redirect response, short circuit and let our Express server
// handle that directly
if (context instanceof Response) {
throw context;
}
let router = createStaticRouter(dataRoutes, context);
return ReactDOMServer.renderToString(
<React.StrictMode>
<StaticRouterProvider
router={router}
context={context}
/>
</React.StrictMode>
);
}Type Declaration
declare function createStaticHandler(
routes: RouteObject[],
opts?: {
basename?: string;
}
): StaticHandler;
interface StaticHandler {
dataRoutes: AgnosticDataRouteObject[];
query(
request: Request,
opts?: {
requestContext?: unknown;
}
): Promise<StaticHandlerContext | Response>;
queryRoute(
request: Request,
opts?: {
routeId?: string;
requestContext?: unknown;
}
): Promise<any>;
}createStaticRouter
createStaticRouter creates a static router for pre-rendering or static site generation, accepting predefined route state instead of dynamically reading from browser history.
import {
createStaticHandler,
createStaticRouter,
StaticRouterProvider,
} from "react-router-dom/server";
import Root, {
loader as rootLoader,
ErrorBoundary as RootBoundary,
} from "./root";
const routes = [
{
path: "/",
loader: rootLoader,
Component: Root,
ErrorBoundary: RootBoundary,
},
];
export async function renderHtml(req) {
let { query, dataRoutes } = createStaticHandler(routes);
let fetchRequest = createFetchRequest(req);
let context = await query(fetchRequest);
// If we got a redirect response, short circuit and let our Express server
// handle that directly
if (context instanceof Response) {
throw context;
}
let router = createStaticRouter(dataRoutes, context);
return ReactDOMServer.renderToString(
<React.StrictMode>
<StaticRouterProvider
router={router}
context={context}
/>
</React.StrictMode>
);
}Type Declaration
declare function createStaticRouter(
routes: RouteObject[],
context: StaticHandlerContext,
opts: {
future?: {
v7_partialHydration?: boolean;
};
}
): Router;RouterProvider
RouterProvider is a component that renders a router, accepting a router instance as its router prop and providing it to child components.
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
children: [
{
path: "dashboard",
element: <Dashboard />,
},
{
path: "about",
element: <About />,
},
],
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
<RouterProvider
router={router}
fallbackElement={<BigSpinner />}
/>
);StaticRouterProvider
StaticRouterProvider is a component used to provide a static router during pre-rendering or static site generation, similar to RouterProvider but designed for static contexts.
import {
createStaticHandler,
createStaticRouter,
StaticRouterProvider,
} from "react-router-dom/server";
import Root, {
loader as rootLoader,
ErrorBoundary as RootBoundary,
} from "./root";
const routes = [
{
path: "/",
loader: rootLoader,
Component: Root,
ErrorBoundary: RootBoundary,
},
];
export async function renderHtml(req) {
let { query, dataRoutes } = createStaticHandler(routes);
let fetchRequest = createFetchRequest(req);
let context = await query(fetchRequest);
// If we got a redirect response, short circuit and let our Express server
// handle that directly
if (context instanceof Response) {
throw context;
}
let router = createStaticRouter(dataRoutes, context);
return ReactDOMServer.renderToString(
<React.StrictMode>
<StaticRouterProvider
router={router}
context={context}
/>
</React.StrictMode>
);
}Type Declaration
declare function StaticRouterProvider(props: {
context: StaticHandlerContext;
router: Router;
hydrate?: boolean;
nonce?: string;
}): JSX.Element;Router Components
BrowserRouter
Type Declaration
declare function BrowserRouter(
props: BrowserRouterProps
): React.ReactElement;
interface BrowserRouterProps {
basename?: string;
children?: React.ReactNode;
future?: FutureConfig;
window?: Window;
}<BrowserRouter> stores the current location in the browser’s address bar using clean URLs and navigates using the browser’s built-in history stack.
import * as React from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
const root = createRoot(document.getElementById("root"));
root.render(
<BrowserRouter>
{/* The rest of your app goes here */}
</BrowserRouter>
);HashRouter
Type Declaration
declare function HashRouter(
props: HashRouterProps
): React.ReactElement;
interface HashRouterProps {
basename?: string;
children?: React.ReactNode;
future?: FutureConfig;
window?: Window;
}<HashRouter> is used in web browsers when the URL should not (or cannot) be sent to the server, such as in some shared hosting environments. It stores the current location in the hash portion of the URL, which is never sent to the server.
import * as React from "react";
import * as ReactDOM from "react-dom";
import { HashRouter } from "react-router-dom";
ReactDOM.render(
<HashRouter>
{/* The rest of your app goes here */}
</HashRouter>,
root
);MemoryRouter
Type Declaration
declare function MemoryRouter(
props: MemoryRouterProps
): React.ReactElement;
interface MemoryRouterProps {
basename?: string;
children?: React.ReactNode;
initialEntries?: InitialEntry[];
initialIndex?: number;
future?: FutureConfig;
}<MemoryRouter> stores its locations in an internal array, unbound to external sources like the browser’s history stack, making it ideal for scenarios requiring full control over the history stack, such as testing.
<MemoryRouter initialEntries>defaults to["/"](a single entry at the root URL).<MemoryRouter initialIndex>defaults to the last index ofinitialEntries.
import * as React from "react";
import { create } from "react-test-renderer";
import {
MemoryRouter,
Routes,
Route,
} from "react-router-dom";
describe("My app", () => {
it("renders correctly", () => {
let renderer = create(
<MemoryRouter initialEntries={["/users/mjackson"]}>
<Routes>
<Route path="users" element={<Users />}>
<Route path=":id" element={<UserProfile />} />
</Route>
</Routes>
</MemoryRouter>
);
expect(renderer.toJSON()).toMatchSnapshot();
});
});NativeRouter
Type Declaration
declare function NativeRouter(
props: NativeRouterProps
): React.ReactElement;
interface NativeRouterProps extends MemoryRouterProps {}<NativeRouter> is the recommended interface for running React Router in React Native applications.
<NativeRouter initialEntries>defaults to["/"](a single entry at the root URL).<NativeRouter initialIndex>defaults to the last index ofinitialEntries.
import * as React from "react";
import { NativeRouter } from "react-router-native";
function App() {
return (
<NativeRouter>
{/* The rest of your app goes here */}
</NativeRouter>
);
}Router
Type Declaration
declare function Router(
props: RouterProps
): React.ReactElement | null;
interface RouterProps {
basename?: string;
children?: React.ReactNode;
location: Partial<Location> | string;
navigationType?: NavigationType;
navigator: Navigator;
static?: boolean;
}StaticRouter
Type Declaration
declare function StaticRouter(
props: StaticRouterProps
): React.ReactElement;
interface StaticRouterProps {
basename?: string;
children?: React.ReactNode;
location?: Path | LocationPieces;
}<StaticRouter> is used to render React Router web applications in Node. The current location is provided via the location prop.
<StaticRouter location>defaults to"/".
import * as React from "react";
import * as ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import http from "http";
function requestHandler(req, res) {
let html = ReactDOMServer.renderToString(
<StaticRouter location={req.url}>
{/* The rest of your app goes here */}
</StaticRouter>
);
res.write(html);
res.end();
}
http.createServer(requestHandler).listen(3000);Route
In React Router v6, the usage of the Route component has changed compared to previous versions. The Switch component is no longer needed; instead, the Routes component wraps all Route components. The Routes component iterates through all Route components and renders the one that matches the current URL.
Route Component Properties
Key properties of the Route component include:
path: Defines the URL path pattern to match.element: Specifies the React element to render when the path matches.index: If set totrue, indicates a default or index route, typically used for top-level components without a specific path.caseSensitive: Controls whether path matching is case-sensitive (defaults tofalse).loader: An asynchronous function for data loading, often used with theuseLoaderDatahook.action: An asynchronous function for handling form submissions, typically used with the<Form>component.
Using Routes and Route
Here’s a basic example using Routes and Route:
import React from 'react';
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';
function App() {
return (
<Router>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/contact">Contact</Link></li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
);
}
export default App;In this example, the Routes component contains three Route components, each corresponding to a page. When a user clicks a navigation link or accesses a URL, Routes finds the first matching Route and renders its element.
Index Route
To define a default child route for a parent route, use the index property:
<Routes>
<Route path="/parent" element={<ParentComponent />}>
<Route index element={<DefaultChildComponent />} />
<Route path="child" element={<SpecificChildComponent />} />
</Route>
</Routes>Here, visiting /parent without a specific subpath renders DefaultChildComponent.
Nested Routes
Route components can be nested to create complex routing structures:
<Routes>
<Route path="/users" element={<UsersLayout />}>
<Route index element={<UsersList />} />
<Route path=":userId" element={<UserProfile />} />
</Route>
</Routes>In this example, UsersLayout serves as a shared container for all child routes, and :userId is a dynamic parameter for matching specific user IDs.
UI Components
Await
The Await component waits for asynchronous data to load before rendering the corresponding component, improving user experience by avoiding flickering or blank content.
import { Await, defer, useLoaderData } from 'react-router-dom';
function Post() {
const post = useLoaderData();
return (
<>
<h1>{post.title}</h1>
<Await resolve={post.content}>
{(content) => <div dangerouslySetInnerHTML={{ __html: content }} />}
</Await>
</>
);
}Form
The Form component handles form submissions, automatically managing submission events and sending form data to the specified URL, simplifying form handling.
import { Form } from 'react-router-dom';
function SearchForm() {
return (
<Form action="/search">
<input type="text" name="q" placeholder="Search..." />
<button type="submit">Search</button>
</Form>
);
}Link
The Link component creates navigation links that trigger client-side navigation without reloading the entire page.
import { Link } from 'react-router-dom';
function Nav() {
return (
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
);
}NavLink
The NavLink component enhances Link by automatically highlighting the active link based on the current URL, ideal for navigation menus.
import { NavLink } from 'react-router-dom';
function Nav() {
return (
<nav>
<ul>
<li><NavLink to="/" end>Home</NavLink></li>
<li><NavLink to="/about">About</NavLink></li>
</ul>
</nav>
);
}Navigate
The Navigate component enables programmatic navigation, triggering navigation through code.
import { Navigate } from 'react-router-dom';
function PrivateRoute({ isLoggedIn }) {
return isLoggedIn ? <Outlet /> : <Navigate to="/login" />;
}Outlet
The Outlet component renders the element of the current Route. In nested routes, Outlet renders the child route’s component matching the current URL.
function Layout() {
return (
<div>
<Nav />
<Outlet />
</div>
);
}Route
The Route component defines a routing rule, specifying the path and component to render.
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>Routes
The Routes component contains multiple Route components, rendering the first Route that matches the current URL.
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Router>
);
}ScrollRestoration
The ScrollRestoration component manages scroll positions, restoring the previous position when users navigate back to a page.
import { ScrollRestoration } from 'react-router-dom';
function App() {
return (
<Router>
<ScrollRestoration />
{/* Other components */}
</Router>
);
}Hook Functions
- useActionData: Retrieves data returned by the last form submission’s action function.
- useAsyncError: Returns errors thrown during loading or action execution.
- useAsyncValue: Retrieves the resolved value awaited by the
Awaitcomponent. - useBeforeUnload: Registers a function called before the user leaves the page, useful for prompting about unsaved changes.
- useBlocker: Registers a function to block or confirm navigation when the user attempts to leave the page.
- useFetcher: Creates a fetcher object for localized data loading and updates.
- useFetchers: Returns an array of all fetchers, managing multiple localized data operations.
- useFormAction: Returns the action method for the current form, enabling manual form submission.
- useHref: Returns the full URL string for a given path.
- useInRouterContext: Checks if the current component is within a router context.
- useLinkClickHandler: Returns a function to handle link clicks, useful for custom link behavior.
- useLinkPressHandler: Similar to
useLinkClickHandlerbut for touch devices. - useLoaderData: Returns data from the current route’s loader function.
- useLocation: Returns the current browser location object, containing URL information.
- useMatch: Returns a match object indicating whether the current URL matches a given path.
- useMatches: Returns an array of match objects for all matched routes.
- useNavigate: Returns a function for programmatic navigation to a new URL.
- useNavigation: Returns the current navigation object with information about ongoing navigation.
- useNavigationType: Returns the type of the current navigation, such as
POPorPUSH. - useOutlet: Returns the component instance rendered by the current
Outlet. - useOutletContext: Returns the context value of the current
Outlet. - useParams: Returns an object containing dynamic parameters from the current URL.
- unstable_usePrompt: An unstable API for displaying a prompt when the user attempts to leave the page.
- useResolvedPath: Returns a resolved path object with complete information for a given path.
- useRevalidator: Provides a method to revalidate the current route’s data.
- useRouteError: Returns the error object for the current route, if any.
- useRouteLoaderData: Returns loader data for the current route and its ancestors.
- useRoutes: Accepts a route array and returns the matched route object.
- useSearchParams: Returns an array with query string key-value pairs and a method to update parameters.
- useSubmit: Returns a function for manually submitting form data.
- unstable_useViewTransitionState: An unstable API for accessing view transition state.
Utility Classes
JSON (JSON Response Handling)
In React Router, json typically refers to parsing JSON data from API responses. When using fetch, axios, or other HTTP libraries in loader or action functions, you may need to parse the response body with response.json().
// In a loader or action
async function fetchUserData() {
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json(); // Parse JSON data
}Redirect
In React Router, redirect typically involves using the Navigate component or useNavigate hook to redirect users to another page based on conditions.
import { Navigate, useNavigate } from 'react-router-dom';
// Using Navigate component
function RedirectToLogin() {
return <Navigate to="/login" />;
}
// Using useNavigate hook
function RedirectToLoginOnLogout() {
const navigate = useNavigate();
useEffect(() => {
const logoutEvent = () => navigate('/login');
window.addEventListener('logout', logoutEvent);
return () => window.removeEventListener('logout', logoutEvent);
}, [navigate]);
}Redirect Document
redirectDocument is not a direct concept in React Router but may refer to redirecting documents in server-side rendering (SSR) or static site generation (SSG) based on API responses. In these scenarios, you might generate HTML documents on the server and redirect using HTTP response headers like Location.
For example, in Next.js, you can use res.writeHead(302, { Location: '/new-url' }) in getServerSideProps or getStaticProps for redirection. In pure React Router applications, you typically rely on client-side routing logic for redirects rather than manipulating HTTP headers.



