Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 50 ยท Production Concerns

Performance and Common Pitfalls

Find out what re-renders when the URL changes, avoid loader waterfalls and needless revalidation, handle big route trees, and fix key and stale-link bugs.

A router sits on the hottest path of your app: every click goes through it. Most React Router apps are fast with no special effort, because matching a URL against a route tree takes microseconds. When a routed app feels slow, the cause is almost never the router itself. It is usually one of four things: components that re-render more than you expect, data that loads one request after another, loaders that run again when nothing changed, or a bundle that ships every page at once.

This lesson walks through those four, then a handful of bugs that look like performance problems but are really mistakes with keys, links and router setup. It is mostly about reasoning, so the real React Router code is read-only, and the live examples are small simulations that you can run to see each effect. If you need a refresher first, read Loaders: Data Before Render and Revalidation and Caching.

What re-renders when the URL changes

When you navigate, the router updates its state, and React re-renders the components that read that state. These hooks subscribe a component to router state:

  • useLocation(), useSearchParams() and useParams() re-render the component when the location, the query string or the params change.
  • useNavigation() re-renders at every phase of a navigation (idle, then loading, then idle again), so a progress bar built on it updates a few times per click.
  • useLoaderData() and useMatches() re-render when the route's data or the match chain changes.

A component that calls none of them is not touched by the router. In a data router, a route's element is created once, when you define the route, so the same element object is handed to React on every render and React skips it unless something it reads has changed. The plain props and context rules of React apply from there. The most common slip is a big layout that calls useLocation() just to highlight one link:

JSX
// Layout.jsx - React Router (read-only)
// Slower: the whole layout re-renders on every navigation.
function Layout() {
  const location = useLocation();
  return (
    <>
      <p>You are on {location.pathname}</p>
      <HugeSidebar />
      <Outlet />
    </>
  );
}

// Better: only the tiny piece that needs the location subscribes.
function CurrentPath() {
  const { pathname } = useLocation();
  return <p>You are on {pathname}</p>;
}

function Layout() {
  return (
    <>
      <CurrentPath />
      <HugeSidebar />
      <Outlet />
    </>
  );
}

The fix is ordinary React: move the hook down to the smallest component that needs it, and wrap expensive children in React.memo when you cannot. For NavLink, you do not need useLocation at all, because it works out its own active state (see Link and NavLink).

flowchart TD
    A["RouterProvider<br/>router state changes"] --> B["Layout<br/>calls useLocation: re-renders"]
    B --> C["HugeSidebar<br/>plain child: re-renders with its parent"]
    B --> D["MemoSidebar<br/>React.memo: skipped"]
    A --> E["Route element created once<br/>no router hooks: skipped"]

Hooks decide who subscribes; memo and stable elements decide who gets skipped.

Real library or stand-in? The code samples above are the real API. The live examples in this lesson use a small hand-written router built on React and location.hash, with a useLocation() hook built on useSyncExternalStore. It reproduces the React rules that matter here (a subscribing component renders on every change, a memoized or stable element does not). The render counts you see are real counts from running React; the loader timings are a simulation with fixed numbers, not a measurement of the real router. The hash-routing idea is explained in Client-Side Routing.

Click through the links below and compare the four counters. The first render counts as 1.

Who re-renders when the location changes?

After two navigations, the plain child and the child that calls useLocation are at 3 renders, while the memoized child and the element created once are still at 1. Data-router route elements behave like the last row, which is why routed pages are not re-rendered just because the URL changed elsewhere.

Do not create the router inside a component

One mistake causes dramatic symptoms: building the router during render.

JSX
// Wrong - React Router (read-only)
function App() {
  const router = createBrowserRouter(routes); // a new router on every render
  return <RouterProvider router={router} />;
}

// Right: create it once, at module level
const router = createBrowserRouter(routes);
function App() {
  return <RouterProvider router={router} />;
}

A new router starts from scratch: loaders run again, pending state resets, and any state kept by the previous router is lost. Create it once outside React. The same applies to routes arrays you pass to useRoutes: define them outside the component, or memoize them.

Loader waterfalls

A waterfall is a chain of requests where each one waits for the previous one to finish. They are the biggest performance problem in routed apps, and they come from three places:

  1. Fetching inside components. The page renders, finds it needs data, starts a request in an effect, and only then renders the child that starts its request. Each level waits for the one above. This is the pattern that loaders exist to remove.
  2. Awaiting one thing after another inside a loader, even when the second does not depend on the first.
  3. A lazy route chunk followed by its loader. If a route's code and its loader come from the same lazy module, the browser must download the code before it can start the data request. See Lazy Routes and Code Splitting.

React Router already runs the loaders of all matched routes in parallel. A parent and a child never wait for each other, which is why nested routes are cheap. The waterfalls that remain are the ones you write yourself:

JSX
// loaders.js - React Router (read-only)

// Waterfall: posts does not need the user, but waits for it anyway.
export async function slowLoader({ params }) {
  const user = await getUser(params.id);
  const posts = await getPosts(params.id);
  return { user, posts };
}

// Parallel: both requests start now.
export async function fastLoader({ params }) {
  const [user, posts] = await Promise.all([getUser(params.id), getPosts(params.id)]);
  return { user, posts };
}

// Streaming (v7): wait only for what the page cannot render without.
export async function streamingLoader({ params }) {
  const userPromise = getUser(params.id);
  const postsPromise = getPosts(params.id);
  return { user: await userPromise, posts: postsPromise };
}

The third version returns a promise inside the object, which the page renders with <Await> and <Suspense> (see Streaming Data with Await and Suspense). When one request truly needs the result of another, you cannot parallelize it, but you can often move the dependency to the server so that one endpoint returns both.

flowchart LR
    N1["Navigate"] --> A1["root: 120 ms"]
    N1 --> A2["dashboard: 200 ms"]
    N1 --> A3["report: 160 ms"]
    A1 --> R1["Render at 200 ms"]
    A2 --> R1
    A3 --> R1
    N2["Navigate"] --> B1["root: 120 ms"] --> B2["dashboard: 200 ms"] --> B3["report: 160 ms"] --> R2["Render at 480 ms"]

The same three requests: in parallel the page waits for the slowest one; in a chain it waits for the sum.

The next example compares three ways to load the same three pieces of data. The durations are fixed numbers, so the result is a simulation of the arithmetic, not a real network test.

Parallel loaders versus waterfalls

Press each button: parallel finishes at 200 ms (the slowest task), awaiting one after another at 480 ms (120 + 200 + 160), and fetching in components at 540 ms, because each level also has to render (a 30 ms gap in this model) before the next one can start its request.

Loaders that run too often

Loaders re-run more often than people expect. By default, a route's loader runs again when:

  • the route's own params change,
  • the search params change (any of them, even ones the loader never reads),
  • you submit an action (or a fetcher mutation),
  • you navigate to the same URL you are already on,
  • you call revalidate() yourself.

That is a safe default, because stale data is a worse bug than an extra request. But a layout loader that fetches the signed-in user will refetch it every time someone types in a search box that updates ?q=. Tell the router when it can skip the work with shouldRevalidate:

JSX
// routes.jsx - React Router (read-only)
{
  id: 'root',
  path: '/',
  loader: userLoader,
  shouldRevalidate: ({ currentUrl, nextUrl, formMethod, defaultShouldRevalidate }) => {
    if (formMethod) {
      return defaultShouldRevalidate; // after a mutation, keep the default
    }
    return currentUrl.pathname !== nextUrl.pathname; // ignore query-string changes
  },
  children: [ /* ... */ ],
}

Keep the rule narrow and keep the default after mutations; an over-eager return false is how stale screens are born. More patterns, including caches and TanStack Query, are in Revalidation and Caching.

Big route trees and bundle size

Matching a URL against the route tree is fast: even with hundreds of routes it is rarely measurable next to rendering and data loading. What does grow with a big app is the JavaScript you ship up front. Your options, in order of payoff:

  1. Split by route. Load a page's code only when someone visits it, with lazy on the route (see Lazy Routes and Code Splitting). Framework mode does this automatically for every route module.
  2. Split by area. Admin screens and rarely used tools should never be in the first download.
  3. Keep the route config light. Import the route's component lazily, not just its loader. A route file that imports a charting library at the top pulls that library into whatever imports the route file.
  4. Preload on intent. Starting the download when the pointer hovers over a link makes the next click feel instant.

Bugs that look like performance problems

The same component for different params

Going from /users/1 to /users/2 renders the same route with new params. React sees the same component type in the same position, so it keeps the instance and its state: a draft, a scroll position, an open dropdown, a half-filled form. This surprises people who expect a fresh page.

The fix is a key that changes with the thing the component represents. Try it: add a note on user 1, move to user 2, then switch the fix on.

State that survives a param change

Without the key, the note count follows you from Ada to Grace. With it, every user gets a fresh component. The real-router version is a key on the element that depends on the param:

JSX
// UserRoute.jsx - React Router (read-only)
function UserRoute() {
  const { id } = useParams();
  return <UserPage key={id} />;
}

Keys are also how you reset a form after a successful action. Do the opposite with care: key={location.pathname} on an Outlet throws away the whole subtree on every navigation, which is sometimes what you want for animations and almost never what you want for performance.

A checklist of common pitfalls

Symptom Likely cause Fix
Whole page flashes on every click Link is a plain <a href>, so the browser reloads the document Use <Link> or <NavLink> for in-app navigation
Redirect flashes the wrong page first useEffect plus navigate() after rendering Throw redirect() from a loader, or render <Navigate>
Data stays stale after saving Mutation sent with plain fetch, so no revalidation Use an action or a fetcher so the router re-runs loaders
List items mix up when sorted or filtered key={index} on rows Use a stable id as the key
State leaks between /x/1 and /x/2 Same component instance reused Add key={id}
Links break when the route moves Hard-coded absolute paths in many places Use relative links, or one helper that builds paths
Everything reloads after a tiny change Router created inside a component Create it once at module level
Missing child pages Parent route has no <Outlet /> Render an Outlet where children should appear

Stale links deserve special mention. A link that was correct at build time can silently turn into a 404 or a full reload after a route is renamed. Keep route paths in one place, prefer relative links inside nested routes (see Relative Links and Relative Routing), and add a catch-all route (see 404 Pages and Catch-All Routes) so a broken link at least lands somewhere helpful. Related debugging tips are collected in Common Mistakes and Debugging.

How to find the real problem

Guessing wastes time. Measure first:

  1. Open the React DevTools Profiler, record one navigation and see which components rendered and why.
  2. Open the browser's Network tab and check whether requests start together (parallel) or in steps (waterfall).
  3. Count how many times a loader runs per click, by logging inside it.
  4. Check the size of the first JavaScript bundle before you optimize anything else.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A big layout component calls useLocation() only to show the current path. What is the best fix to avoid re-rendering the whole layout on every navigation?

    A component re-renders when a hook it uses changes. Moving the hook into a tiny child means only that child updates, while the rest of the layout is left alone.
  2. 2. Nested routes /dashboard and /dashboard/report both have loaders. How does React Router run them?

    Loaders of all matched routes start together to avoid waterfalls. A waterfall only appears when you create one yourself, for example by awaiting independent requests in sequence inside a loader.
  3. 3. A loader fetches the user and then the posts with two awaits in a row, though posts does not need the user. What should you change?

    Independent requests should start at the same time. Promise.all cuts the wait from the sum of both durations to the longer of the two.
  4. 4. You open /users/1, type a note into the page, then click a link to /users/2. The note is still there. Why?

    React keeps a component instance when its type and position stay the same. A key tied to the param tells React that a different user means a different instance.
  5. 5. Why is calling createBrowserRouter inside the App component a bug?

    The router owns navigation state and data. Creating it again on each render throws that state away, so create it once at module level.

Summary

  • Router hooks subscribe components to router state; keep them in small components, and use React.memo or stable elements to skip expensive subtrees.
  • Create the router once at module level, never inside a component.
  • Route loaders run in parallel; waterfalls come from fetching in effects, sequential awaits and code-then-data chains. Use Promise.all or return promises for streaming.
  • By default loaders re-run on param, search param and same-URL changes and after actions; narrow this with a careful shouldRevalidate.
  • For large apps, split by route and area, keep route files light and preload on intent.
  • Same-route navigation reuses component state; add key={id} when the page represents a specific record.
  • Profile before optimizing: React Profiler, the Network tab and logging inside loaders.

Next: Framework Mode Overview