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

Common Pitfalls: Redirect Loops and Flash

Avoiding infinite redirects and content flashing by properly sequencing auth checks, suspense, and redirects.

Common Pitfalls: Redirect Loops and Flash

You'll learn how to avoid infinite redirect loops and authentication content flashing by properly sequencing your checks and state management.

The Problem: When Protection Goes Wrong

Protected routes can backfire in two frustrating ways. Redirect loops happen when your auth check redirects to login, but login redirects back to the protected page, creating an endless cycle. Content flashing occurs when protected content briefly appears before the auth check completes and redirects the user away.

Think of it like a security guard who checks your badge after opening the door—you glimpse inside before being kicked out. Or worse, two guards who keep sending you back and forth between entrances forever.

The Root Causes

Redirect loops often stem from:

  • Login routes that check auth and redirect authenticated users
  • Inconsistent auth state between client and server
  • Missing "loading" states that cause premature decisions

Content flashing happens when:

  • Components render before useLoaderData or auth checks complete
  • No Suspense boundary handles loading states
  • Conditional redirects inside components after initial render

The Solution Pattern

Sequence your protection layers correctly:

  1. Loader-level checks first: Use loaders to check auth before rendering
  2. Loading states: Show spinners while auth is being verified—don't render OR redirect
  3. Conditional logic: Only render <Navigate> after you're certain auth has resolved
  4. Consistent checks: Use the same auth source everywhere (don't mix server state with stale client state)

For loaders, return redirects immediately—React Router handles them before rendering. For component-level checks with useOutletContext, ensure your auth data includes a loading state and wait for it to resolve.

Key Takeaway: Prevent redirect loops by checking auth consistently in one place (preferably loaders), and eliminate flashing by never rendering protected content until auth state has fully loaded—use loading indicators during the verification window.