Course contentsShow
← React
Lesson 1854 of 2,39643. RoutingFree lesson

shouldRevalidate for Fine-Grained Control

Customizing which loaders rerun after actions or navigation using shouldRevalidate functions.

shouldRevalidate for Fine-Grained Control

What you'll learn: How to customize exactly which loaders rerun after actions or navigation using shouldRevalidate functions.

By default, React Router's data routers automatically revalidate (re-fetch) all active loaders after an action completes or when certain navigation events occur. This is usually what you want—keeping your UI fresh—but sometimes it's overkill. Maybe you know a particular loader's data couldn't possibly have changed, or you want to prevent unnecessary network requests for performance reasons.

The Core Idea

The shouldRevalidate function is an optional export from your route module that gives you fine-grained control over when that route's loader should rerun. Think of it as a filter: React Router asks "should I revalidate this loader?" and your function returns true (yes, refetch) or false (skip it, use cached data).

export function shouldRevalidate({ 
  currentUrl, 
  nextUrl, 
  formMethod, 
  defaultShouldRevalidate 
}) {
  // Only revalidate if we just submitted a form
  if (formMethod && formMethod !== "GET") {
    return true;
  }
  
  // Don't revalidate on same-page navigation
  if (currentUrl.pathname === nextUrl.pathname) {
    return false;
  }
  
  // Fallback to default behavior
  return defaultShouldRevalidate;
}

The function receives context about the navigation: where you're coming from (currentUrl), where you're going (nextUrl), whether a form was submitted (formMethod), and the default revalidation decision. You can inspect these values and decide accordingly.

Use case example: An expensive analytics loader that only needs fresh data when users explicitly refresh, not after every action.

Key Takeaway: Use shouldRevalidate to optimize data loading by preventing unnecessary loader calls when you know the data hasn't changed, giving you surgical control over React Router's automatic revalidation behavior.