Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 50 ยท Data Mode

Revalidation and Caching

Learn when React Router re-runs loaders, skip needless refetches with shouldRevalidate, refresh stale data with useRevalidator, and pair loaders with TanStack Query.

Loader data is a snapshot. The router calls a loader, stores what it returned, and every component that reads it with useLoaderData sees that same snapshot until the router decides to ask again. Asking again is called revalidation, and getting it right is what keeps a data-router app both correct and fast: too little revalidation and users stare at stale numbers, too much and every click triggers a wave of identical requests.

The good news is that the defaults are sensible. After you change something the screen updates itself, and you rarely have to think about it. This lesson explains exactly when loaders re-run, how to opt out for specific routes with shouldRevalidate, how to refresh on demand with useRevalidator (for polling or window focus), and how loaders fit with a client cache such as TanStack Query. It assumes you know loaders and actions.

When loaders run

On a navigation, the router runs the loaders of the routes that are new in the matched tree. After that it keeps them. A loader runs again in these situations:

  1. After an action. Any submission to an action (a Form, a fetcher, or submit) is followed by a revalidation of all active loaders, because the router cannot know what the mutation changed.
  2. When the URL's search params change. Moving from /products?sort=price to /products?sort=name re-runs the loaders on the page, because a loader may read the query string.
  3. When a route's own params change. Going from /users/1 to /users/2 re-runs the loader of the users/:id route, but not its parent layout's loader, whose params did not change.
  4. When you click a link to the URL you are already on. That counts as an explicit request to refresh.
  5. When you ask for it with revalidator.revalidate().

Navigating between two sibling pages under the same layout does not re-run the layout's loader. That is a cache of sorts: the layout's data is shared by all the pages beneath it.

flowchart TD
    A["Something happens<br/>(action, URL change, link click, revalidate call)"] --> B["For each active route with a loader"]
    B --> C["Compute defaultShouldRevalidate"]
    C --> D{"Route exports<br/>shouldRevalidate?"}
    D -->|"no"| E["Use the default"]
    D -->|"yes"| F["Your function decides<br/>(true or false)"]
    E --> G["Run the loader, or keep its data"]
    F --> G

The router computes a default answer for every active loader. A shouldRevalidate function on the route can overrule it in either direction.

shouldRevalidate: opting out

Suppose a page loads all of a user's orders from a slow endpoint and shows them in tabs, with the current tab stored in ?tab=. Switching tabs changes the search params, so by default the loader runs again, fetching exactly the same orders. You can say that a change of tab alone is not worth a refetch.

Export a shouldRevalidate function from the route (or set it in the route object). It receives details of what just happened and returns a boolean:

JSX
// orders.jsx - React Router (read-only)
export function shouldRevalidate({
  currentUrl,
  nextUrl,
  formMethod,
  defaultShouldRevalidate,
}) {
  // after a mutation, trust the default
  if (formMethod && formMethod !== 'GET') {
    return defaultShouldRevalidate;
  }

  // ignore changes that only touch ?tab
  const strip = (url) => {
    const params = new URLSearchParams(url.search);
    params.delete('tab');
    return url.pathname + '?' + params;
  };
  if (strip(currentUrl) === strip(nextUrl)) {
    return false;
  }

  return defaultShouldRevalidate;
}

In a route object you write the same thing as a property: { path: 'orders', loader, shouldRevalidate }. The other arguments are currentParams and nextParams, formAction, formData, and actionResult (what the action just returned, handy for "only refetch if the action reported a change").

The golden rule: start from defaultShouldRevalidate and only override the cases you understand. Returning false after a mutation is how apps end up showing stale data that "fixes itself on refresh".

Real library or stand-in? The react-router code is the real API. The live examples use a small hand-written loader runner on React and location.hash that mimics the revalidation decision: it calls a shouldRevalidate function with currentUrl, nextUrl and defaultShouldRevalidate the way the real router does. The real router runs this for every route in the tree, not just one, and covers params and form submissions, which the stand-in leaves out.

Skip refetching when only the tab changes

Click "Done" and "Open" a few times with the checkbox off: every tab click is a loader call, although the list of orders never changes. Turn the checkbox on and repeat: the log says "skipped revalidation" and the loader count stays put. The filtering still works because the component reads ?tab from the URL itself and filters the loaded orders.

useRevalidator: refresh on demand

Sometimes the data changes on the server without the user doing anything: another person edits a record, a job finishes, a price ticks. The router cannot know, so you tell it. useRevalidator() returns { revalidate, state }, where state is "idle" or "loading":

JSX
// live-dashboard.jsx - React Router (read-only)
import { useEffect } from 'react';
import { useLoaderData, useRevalidator } from 'react-router';

export default function Dashboard() {
  const stats = useLoaderData();
  const revalidator = useRevalidator();

  // refresh when the tab becomes visible again
  useEffect(() => {
    function onVisible() {
      if (document.visibilityState === 'visible') {
        revalidator.revalidate();
      }
    }
    document.addEventListener('visibilitychange', onVisible);
    return () => document.removeEventListener('visibilitychange', onVisible);
  }, [revalidator]);

  return (
    <section>
      <button onClick={() => revalidator.revalidate()} disabled={revalidator.state === 'loading'}>
        {revalidator.state === 'loading' ? 'Refreshing...' : 'Refresh'}
      </button>
      <p>Active users: {stats.activeUsers}</p>
    </section>
  );
}

The same hook works with an interval for polling or with a WebSocket message handler ("something changed, reload"). Revalidation re-runs the active loaders only and keeps the old data on screen until the new data arrives, so there is no flash: the page simply swaps numbers. Use revalidator.state for a subtle "refreshing" indicator (the same idea as pending UI).

The next example shows stale data and the two ways it gets fixed: your own action (which revalidates automatically) and a manual refresh (for changes made by someone else).

Stale data, actions and revalidate()

Press "A teammate adds a task": the server count rises to 3 but the page still lists 2. That is stale data. Press "Revalidate" and watch revalidator.state go to loading and back while the old list stays visible, then the new list appears. Press "Add my task (action)" and the list updates without any extra click, because an action is always followed by revalidation.

Caching: what the router does and does not do

React Router does not have a data cache. It remembers the data of the active routes, and it re-runs loaders according to the rules above, but if you leave a page and come back an hour later, the loader runs again. That is usually what you want, but it has consequences:

  • Back and forward navigations call loaders again unless the route is still active.
  • Two routes that fetch the same resource each make their own request.
  • Anything you want cached across navigations needs a cache you provide.

There are three common places for that cache:

  • The HTTP cache. If your API sends Cache-Control headers, the browser's own cache already answers repeated fetch calls. This costs nothing in your code.
  • A module-level map or memoized function, for small, safe-to-share data such as a list of countries.
  • A client cache library such as TanStack Query, which adds freshness times, deduplication, background refetching and invalidation.

Loaders with TanStack Query

TanStack Query and React Router solve different halves of the problem. The router decides when data is needed (before the route renders). The cache decides whether a request is needed. The usual pairing has the loader ask the cache, and the component read from the same cache:

JSX
// product.jsx - React Router + TanStack Query (read-only, needs @tanstack/react-query)
import { useLoaderData, useParams } from 'react-router';
import { useQuery, queryOptions } from '@tanstack/react-query';

const productQuery = (id) =>
  queryOptions({
    queryKey: ['product', id],
    queryFn: () => fetch(`/api/products/${id}`).then((r) => r.json()),
    staleTime: 60_000,
  });

// returns a function so the loader can reach the query client
export const loader = (queryClient) => async ({ params }) => {
  return queryClient.ensureQueryData(productQuery(params.id)); // cache hit: no request
};

export default function Product() {
  const { id } = useParams();
  const initialData = useLoaderData();
  const { data: product } = useQuery({ ...productQuery(id), initialData });
  return <h1>{product.name}</h1>;
}

// in an action: update the server, then mark the cached data stale
export const action = (queryClient) => async ({ request, params }) => {
  await saveProduct(params.id, await request.formData());
  await queryClient.invalidateQueries({ queryKey: ['product', params.id] });
  return null;
};

The flow: the first visit misses the cache and fetches; later visits within staleTime get the cached value instantly, which makes the navigation feel immediate. Router revalidation after an action calls ensureQueryData again, but because the action invalidated that key, it refetches exactly the data that changed and nothing else. For the deeper treatment of the cache side, see TanStack Query in depth and Caching and server state.

flowchart LR
    A["Navigation"] --> B["loader"]
    B --> C{"In the query cache<br/>and fresh?"}
    C -->|"yes"| D["Return cached data"]
    C -->|"no"| E["Fetch, store, return"]
    D --> F["Route renders"]
    E --> F
    G["action"] --> H["invalidateQueries"]
    H --> B

The router asks the cache through the loader. An action invalidates entries, and the revalidation it triggers refetches only what is stale.

Rules of thumb

  • Trust the defaults, then add shouldRevalidate only where you can name the wasted request.
  • Always start from defaultShouldRevalidate, and never return false after a mutation unless you refresh the data another way.
  • Use useRevalidator for changes the router cannot see: polling, focus, sockets.
  • Do not store loader data in component state (see pitfalls): you would be copying a snapshot that revalidation is trying to replace.
  • If you need a real cache, bring one. The router intentionally does not.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user submits a form whose action succeeds. What does React Router do next with the loaders on screen?

    After any action the router cannot know what changed, so by default it re-runs every active loader. You can narrow this with shouldRevalidate.
  2. 2. Navigating from /users/1/posts to /users/1/settings, both children of a users/:id layout route. Does the layout route's loader run again by default?

    Loaders of routes that stay active are kept. The layout's loader only re-runs when its own params change, the search params change, an action runs, you click the same URL, or you call revalidate.
  3. 3. Which shouldRevalidate implementation is the safest way to skip refetching when only ?tab changed?

    Targeted overrides keep the default behaviour for everything else, including mutations. Returning false unconditionally leaves stale data after actions.
  4. 4. Which tool lets you refresh loader data when the browser tab becomes visible again?

    The router cannot see changes made elsewhere, so you trigger revalidation yourself. revalidate() re-runs the active loaders and keeps the old data visible until the new data arrives.
  5. 5. What is true about caching in React Router itself?

    The router remembers the data for routes that are currently active and re-runs loaders per the revalidation rules. Cross-navigation caching is up to you.

Summary

  • Loader data is a snapshot that is replaced by revalidation: after actions, on search or param changes, on same-URL links and on revalidate().
  • Routes that stay active between navigations keep their data, so a layout's loader does not re-run for sibling pages.
  • shouldRevalidate receives currentUrl, nextUrl, formMethod, actionResult and defaultShouldRevalidate; override narrowly and fall back to the default.
  • useRevalidator() gives revalidate() and state for polling, focus refresh and push-style updates; old data stays visible while it loads.
  • The router has no cross-navigation cache: rely on HTTP caching or a library such as TanStack Query, with the loader calling ensureQueryData and actions calling invalidateQueries.

Next: Error Boundaries and Error Elements