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

Outlet Context for Auth Data

Passing authenticated user data down through nested protected routes using React Router's Outlet context.

Outlet Context for Auth Data

You'll learn how to pass authenticated user data down through nested protected routes using React Router's Outlet context, eliminating the need for prop drilling or redundant context providers.

The Problem: Sharing Auth Data with Nested Routes

When you have protected routes with nested children, those child components often need access to the authenticated user's data. You could fetch it again, use a separate Context Provider, or prop-drill through multiple layers — but there's a cleaner way.

The Outlet Context Solution

React Router's <Outlet> component accepts a context prop. Any data you pass here becomes available to all child routes through the useOutletContext hook. This is perfect for sharing auth data that's already been validated in your parent loader.

Think of it like a parent route putting user data on a shelf that all child routes can reach up and grab from — no need to pass it through each level explicitly.

How It Works

In your protected layout route, pass the authenticated user to Outlet:

function ProtectedLayout() {
  const user = useLoaderData(); // From parent loader

  return (
    <div>
      <nav>Welcome, {user.name}</nav>
      <Outlet context={{ user }} />
    </div>
  );
}

In any child route component:

function Dashboard() {
  const { user } = useOutletContext();
  
  return <h1>{user.name}'s Dashboard</h1>;
}

This pattern keeps your auth data flowing naturally down the route tree without additional infrastructure. It's type-safe (with TypeScript), performant, and follows React Router's architectural patterns.

Key Takeaway: Use <Outlet context={{ user }}> in protected layouts and useOutletContext() in child routes to share authenticated user data cleanly through nested route hierarchies without prop drilling or separate context providers.