Routing and code splitting in React
A router maps URLs to components. Nested routes share layouts, lazy routes split the JavaScript so each page loads only its own code, loaders start data requests before rendering so there is no waterfall, and error boundaries stop one broken part from turning the whole page white. These four ideas cover most routing questions in an interview.
Author: bezzad
Contents
The problem: a slow first page and a white screen
Our shop is one React app. The team got three reports:
- The home page is slow on phones. The JavaScript file is 1.4 MB. It has the code of every page, including the admin panel that only 5 people use.
- The order page shows three spinners, one after another. First the page loads the order, then the items, then the shipping status.
- A bug in the reviews widget turns the whole product page white. The user cannot even add the product to the cart.
All three are routing problems. Let us fix them one by one.
A router maps URLs to components
In a single-page app, the router reads the URL and decides which components to show. Clicking a link changes the URL with the History API, without a full page reload.
import { createBrowserRouter, RouterProvider } from 'react-router';
const router = createBrowserRouter([
{
path: '/',
Component: ShopLayout, // header, cart, footer
children: [
{ index: true, Component: HomePage },
{ path: 'products/:id', Component: ProductPage },
{ path: 'orders/:id', Component: OrderPage },
],
},
]);
export function App() {
return <RouterProvider router={router} />;
}
- Nested routes: ShopLayout is the parent. It renders the header and the footer once, and an
<Outlet />where the child page goes. When the user moves between child pages, the layout stays and keeps its state. - URL params:
:idis a param. The page reads it with the useParams hook. - Links: use the Link component, not a plain
<a>, so the router handles the click without a reload. Links stay real anchors in the HTML, so they still work with the keyboard, a middle click and screen readers.
Code splitting: load only what the page needs
import { lazy, Suspense } from 'react';
const AdminPage = lazy(() => import('./admin/AdminPage'));
function AdminRoute() {
return (
<Suspense fallback={<p>Loading…</p>}>
<AdminPage />
</Suspense>
);
}
import()with parentheses is a dynamic import. The bundler (Vite, webpack) puts that file and what it imports into a separate chunk.- lazy makes a component from that import. The first time it renders, React waits for the chunk and shows the nearest Suspense fallback.
- React Router also has a
lazyfield on a route, which loads the component and its loader together. Use the way your router and framework recommend. - Split by route first. Routes are natural borders: a user on the home page does not need the checkout code. Then split big widgets that are not visible at first, like a map or a rich text editor.
- Do not split too small. Every chunk is one more request. Many tiny chunks can be slower than one medium file.
- Prefetch the next likely page, for example when the user hovers a link or when the browser is idle, so the click feels instant.
Loaders: fetch before render, not after
When each component fetches its data in useEffect, a child cannot start before its parent has finished loading and rendering. This is a request waterfall: three requests of 300 ms take 900 ms.
const router = createBrowserRouter([
{
path: 'orders/:id',
Component: OrderPage,
loader: async ({ params }) => {
// All three start at the same time.
const [order, items, shipping] = await Promise.all([
getOrder(params.id!),
getItems(params.id!),
getShipping(params.id!),
]);
return { order, items, shipping };
},
},
]);
function OrderPage() {
const { order, items, shipping } = useLoaderData();
// ...
}
- The router calls the loader when the navigation starts, before the page renders. The requests run in parallel.
- The page gets the data with useLoaderData. There are no loading flags inside the component.
- If one part is slow and not important (for example the reviews), do not await it. Return the promise and show it inside a Suspense boundary, so the rest of the page shows first.
- TanStack Query and frameworks like Next.js have the same idea: start the request as early as possible, at the route level, not deep inside the tree.
Error boundaries: one broken part, not a white page
When a component throws during render, React removes the whole tree up to the nearest error boundary. With no boundary, the whole app disappears.
import { ErrorBoundary } from 'react-error-boundary';
function ProductPage() {
return (
<>
<ProductDetails />
<AddToCartButton />
<ErrorBoundary fallback={<p>Reviews are not available now.</p>}>
<Reviews />
</ErrorBoundary>
</>
);
}
- An error in Reviews now shows a small message. The product details and the buy button keep working.
- In React Router, each route can have an ErrorBoundary (or errorElement). It catches errors in that route’s loader and component, and the parent layout stays.
- Error boundaries do not catch errors in event handlers, in timers, or in async code outside render. Handle those with try/catch and show the error with state.
- Report every caught error to your logging or monitoring tool. A boundary hides the error from the user, not from you.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| All pages in one bundle | Slow first load, mostly on phones. | Lazy routes, split by route first. |
| lazy() called inside a component | A new component on every render, state is lost. | Call lazy at the top level of a module. |
| Fetching in nested effects | A waterfall of spinners. | Route loaders, or start requests in parallel at the top. |
| No error boundary | One bug turns the whole page white. | A boundary per route and around risky widgets. |
Plain <a> for internal links |
Full page reload, app state is lost. | The router’s Link component. |
| Filters kept outside the URL | Back and share do not work. | Search params. |
Summary in 6 lines
- A router maps URLs to components. Nested routes share a layout that stays on screen.
- Split the JavaScript by route with lazy and Suspense, and prefetch the likely next page.
- Do not split into tiny pieces. Each chunk is one more request.
- Start data requests at the route level, in parallel, before rendering. Avoid effect waterfalls.
- Put an error boundary on each route and around risky widgets, and report the errors.
- Error boundaries catch render errors only. Event handler and async errors need try/catch.