How does client-side routing work in React?
IntermediateReact interview questionBy UIRound, updated 17 November 2026
Short answer
Client-side routing lets a single-page app change the URL and the screen without asking the server for a new HTML page. A router intercepts link clicks, calls history.pushState() to update the address bar, and re-renders the component that matches the new path. It listens for popstate to handle the Back and Forward buttons. The server must still return index.html for any deep link.
The browser APIs underneath
Every React router is built on the History API.
history.pushState(state, "", url)changes the URL and adds an entry to the session history. The browser does not load anything, and no event fires.history.replaceState(state, "", url)changes the URL without adding an entry. Routers use it for redirects and for updating search params.- The
popstateevent fires onwindowwhen the user moves through history with Back or Forward, or when code callshistory.back(). It does not fire forpushState. location.pathnameandlocation.searchhold the current path and query string.
Because pushState fires no event, a router has to notify its own subscribers when it navigates, and listen to popstate for everything else.
A tiny router
This is enough to show the whole mechanism. Real routers add matching, nesting, data loading and many edge cases.
import { useSyncExternalStore } from "react";
const listeners = new Set();
function subscribe(callback) {
listeners.add(callback);
window.addEventListener("popstate", callback);
return () => {
listeners.delete(callback);
window.removeEventListener("popstate", callback);
};
}
export function navigate(to) {
history.pushState(null, "", to);
listeners.forEach((callback) => callback()); // pushState fires no event
}
export function usePathname() {
return useSyncExternalStore(subscribe, () => location.pathname);
}
export function Link({ to, ...props }) {
function handleClick(event) {
// Let the browser handle new tabs, downloads and non-left clicks
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
navigate(to);
}
return <a {...props} href={to} onClick={handleClick} />;
}
const routes = [
{ pattern: /^\/$/, render: () => <Home /> },
{ pattern: /^\/users\/(?<id>[^/]+)$/, render: ({ id }) => <UserPage id={id} /> },
];
export function App() {
const pathname = usePathname();
for (const route of routes) {
const match = pathname.match(route.pattern);
if (match) return route.render(match.groups ?? {});
}
return <NotFound />;
}The URL is external state that lives in the browser, so useSyncExternalStore is the right hook to read it. When the path changes, App re-renders and picks a different component. Nothing reloads, so React state, open connections and cached data survive the navigation.
Links vs plain anchors
A plain <a href="/users/42"> makes the browser request a new document. The whole app unloads, JavaScript runs again from scratch, and all in-memory state is lost. A router's Link renders a real <a> with a real href, then cancels the default and navigates in JavaScript.
Keeping a real anchor matters. It is focusable, screen readers announce it as a link, the user can copy or middle-click it into a new tab, and it still works if JavaScript fails. Never build navigation from a div or button with an onClick that calls navigate.
Nested routes and layouts
Real apps share layouts: a dashboard with a sidebar whose inner page changes. Routers model this as a tree of routes. A parent route renders its layout and a placeholder (often called an outlet) where the matching child route appears. When you move from /dashboard/settings to /dashboard/billing, only the child changes, so the sidebar keeps its state and does not remount.
Matching follows the same tree. The router matches the URL segment by segment and ranks routes by specificity. In most routers, /users/new wins over /users/:id whatever order you declare them in.
Code splitting per route
Routes are the natural place to split the bundle. Users of the home page do not need the code for the settings page.
import { lazy, Suspense } from "react";
const Settings = lazy(() => import("./pages/Settings"));
<Suspense fallback={<PageSpinner />}>
<Settings />
</Suspense>The chunk downloads the first time the route renders. Many routers also preload it on hover or focus of the link. See How do code splitting and React.lazy work?.
The server must serve index. html for deep links
Client-side routing only works once the app has loaded. If a user opens https://example.com/users/42 directly, or refreshes on that page, the browser asks the server for /users/42. A plain static server has no such file and returns 404.
The fix is a fallback rule: for any path that is not a real file, return index.html, and let the router handle the path. Most static hosts and dev servers have a setting for this. Keep real 404s for missing assets such as /app.js, so a broken script does not get HTML back.
Hash routing (/#/users/42) avoids the problem because the server never sees the part after #, but the URLs are uglier and worse for search engines. Frameworks with server rendering, such as Next.js, solve it differently: every route exists on the server, as covered in App Router vs Pages Router.
Practise it
Implement a basic client-side router using the History API builds the mechanism above, and Build a route matcher with params, optional segments and wildcards adds ranking. Build nested route loaders and actions, Lazy-load route components with React.lazy and Restore scroll positions in a single-page app cover what real routers add.
Common follow-up questions
What does a router do about scroll and focus?
The browser resets scroll on a full page load, but not on pushState. Routers scroll to the top on new navigations and restore the saved position on Back. For accessibility, they should also move focus to the new page's heading or announce the change, because a screen reader otherwise hears nothing.
Where should filters and pagination live?
In the URL's search params, so a link or refresh shows the same view. Use replaceState for changes that should not each create a history entry, such as typing in a search box.
How do protected routes work?
The route checks the auth state before rendering. If the user is not signed in, it redirects with replace so Back does not return to the blocked page. The server must still check permissions, because client checks are only for the user experience.
Is there anything newer than the History API?
The Navigation API gives a single navigate event for every navigation, including link clicks. Browser support has been growing, so check it before relying on it; routers still use the History API underneath.
Mistakes to avoid
Using
onClickon adivinstead of a real link with anhrefForgetting that
pushStatedoes not firepopstateDeploying without a fallback to
index.html, so refreshes return 404Intercepting Ctrl+click and middle-click, which breaks "open in new tab"
Storing view state such as filters only in React state, so links cannot share it
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Implement a basic client-side router using the History APIMedium45 min
- Build a route matcher with params, optional segments and wildcards, ranked by specificityMedium35 min
- Build nested route loaders and actions: parallel loading,
<Outlet>, pending UI, aborts and revalidationHard60 min - Lazy-load route components with React.lazy, preload on hover and retry failed chunksMedium40 min
- Restore scroll positions in a single-page app: save per history entry, restore on Back, reset on new navigationMedium40 min