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

Loading States During Auth Checks

Handling async auth verification gracefully with loading indicators to avoid flashing content or redirects.

Loading States During Auth Checks

What you'll learn: How to prevent content flashing and jarring redirects by showing loading indicators while verifying a user's authentication status.

The Problem

When you check if a user is authenticated (especially with async operations like token validation or API calls), there's a brief moment where you don't know yet if they're logged in. If you immediately render protected content or redirect them, users see a disorienting flash—the page appears, then vanishes, or they bounce between routes.

The Solution Pattern

Introduce a loading state during authentication verification. While checking auth status (whether in a loader, a component effect, or a context provider), display a spinner or skeleton screen instead of making decisions prematurely.

Think of it like a bouncer checking IDs at a club entrance. You don't send someone to the VIP area or the exit until the ID check completes—they wait at the door.

Common Implementation Points

In a component:

function ProtectedRoute({ children }) {
  const { user, isLoading } = useAuth();
  
  if (isLoading) {
    return <LoadingSpinner />;
  }
  
  if (!user) {
    return <Navigate to="/login" />;
  }
  
  return children;
}

In a loader:

async function protectedLoader() {
  const authCheck = checkAuthStatus(); // Returns promise
  
  if (authCheck.isLoading) {
    // Return loading indicator data
    return { loading: true };
  }
  
  // Now safely decide to redirect or load data
}

The key is waiting for the auth check to complete before making routing decisions. This prevents the "flash of wrong content" problem.

Key Takeaway: Always show a loading state while authentication status resolves asynchronously—never render protected content or redirect until you know the user's auth state, preventing jarring user experiences.