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

useOutletContext: Sharing Data with Children

Passing data from a parent layout route to any nested child route using the Outlet context prop.

useOutletContext: Sharing Data with Children

What you'll learn: How to pass data from a parent layout route down to any nested child route using React Router's Outlet context.

The Problem

You've built nested routes with <Outlet /> rendering your child components. But what if your parent layout needs to share data with those children—like user info, theme settings, or shared handlers? Props won't work because you're not directly rendering the child components; the router is.

The Solution: Outlet Context

React Router lets you pass a context value through the <Outlet /> component. Think of it like a delivery chute: the parent drops data into the outlet, and any child route can reach up and grab it.

In the parent layout route:

import { Outlet } from 'react-router-dom';

function DashboardLayout() {
  const user = { name: 'Alice', role: 'admin' };
  const logout = () => { /* logout logic */ };

  return (
    <div>
      <nav>Dashboard Nav</nav>
      <Outlet context={{ user, logout }} />
    </div>
  );
}

In any child route:

import { useOutletContext } from 'react-router-dom';

function ProfilePage() {
  const { user, logout } = useOutletContext();

  return (
    <div>
      <h1>Welcome, {user.name}!</h1>
      <button onClick={logout}>Logout</button>
    </div>
  );
}

How It Works

The context prop on <Outlet /> accepts any value—an object, array, or single value. The useOutletContext hook in child routes retrieves it. This pattern works across multiple nesting levels; each child gets the context from its immediate parent outlet.

When to Use It

Use outlet context for layout-specific data that multiple child routes need. For app-wide state, Context API or state management libraries are better. This is purely for parent-to-children communication within a route hierarchy.

Key Takeaway: useOutletContext lets parent layout routes pass data through <Outlet context={value} /> to any nested child route, solving the "how do I share layout data?" problem cleanly.