Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 50 ยท Nested Routes and Layouts

Passing Data Down with Outlet Context

Pass state from a layout route to its child pages with the context prop of Outlet and useOutletContext, and learn when a loader or React context fits better.

A layout route often owns something its pages need. A settings layout holds the form values that several tabs edit. An account layout knows the signed-in user. A dashboard layout keeps the selected date range. The pages are children of that layout, rendered by the router inside <Outlet />, so you cannot write <Profile user={user} /> yourself: you never create the child element. How does the data get from parent to child?

React Router has a small built-in answer: give the Outlet a context prop, and read it in the child with the useOutletContext() hook. It is ordinary React context with a router-shaped interface. This lesson shows how it works, the one rule that surprises people (it reaches only one level), how to avoid needless re-renders, and when you should reach for something else: a loader, or your own context provider. If you want a refresher on plain React context first, read Context.

Outlet context in three steps

This is the real API (read-only, because the live editor cannot install packages):

JSX
// SettingsLayout.jsx - React Router (read-only)
import { useMemo, useState } from 'react';
import { Outlet, NavLink } from 'react-router';

export default function SettingsLayout() {
  const [settings, setSettings] = useState({ name: 'Ada', theme: 'light' });
  const value = useMemo(() => ({ settings, setSettings }), [settings]);

  return (
    <div>
      <h1>Settings for {settings.name}</h1>
      <nav>
        <NavLink to="profile">Profile</NavLink>
        <NavLink to="appearance">Appearance</NavLink>
      </nav>
      <Outlet context={value} />
    </div>
  );
}
JSX
// Profile.jsx - React Router (read-only)
import { useOutletContext } from 'react-router';

export default function Profile() {
  const { settings, setSettings } = useOutletContext();
  return (
    <input
      value={settings.name}
      onChange={(e) => setSettings({ ...settings, name: e.target.value })}
    />
  );
}
  1. The layout owns the state and passes a value through <Outlet context={value} />.
  2. The router renders the matching child inside the Outlet and makes that value available to it.
  3. The child calls useOutletContext() and gets exactly what the layout passed. It can read values and call the functions you included, such as setSettings.
flowchart LR
    S["SettingsLayout<br/>owns state"] -->|"context prop"| O["Outlet"]
    O --> P["Profile page<br/>useOutletContext()"]
    O --> A["Appearance page<br/>useOutletContext()"]
    P -.->|"setSettings"| S
    A -.->|"setSettings"| S

Data flows down through the Outlet; changes flow back up by calling a function that the layout passed down.

Real library or stand-in? The code above is the real API. The live examples use a small hand-written router built on React and location.hash (the sandbox has no packages): a list of route objects, a matcher, and an Outlet that accepts a context prop and provides it through React context, just like the real one. useOutletContext in the stand-in is a one-line useContext call.

A layout sharing state with its pages

Open "Profile", type a new name, then open "Appearance" and switch the theme. The heading, which lives in the layout, always shows both values. The two pages never talk to each other: each reads and writes the layout's state through the Outlet, and the state survives moving between tabs because the layout stays mounted (see Nested Routes and Outlet).

The one-level rule

Outlet context is provided by each Outlet to the route it renders. A grandchild does not see the layout's context unless the middle layout passes it along. Think of it as a hand-off, not a broadcast:

JSX
// MiddleLayout.jsx - React Router (read-only)
import { Outlet, useOutletContext } from 'react-router';

export default function MiddleLayout() {
  const context = useOutletContext();
  return (
    <section>
      <h2>Middle layout</h2>
      <Outlet context={context} />
    </section>
  );
}

A middle layout can also add to the value: <Outlet context={{ ...context, extra }} />. If it does neither, its own <Outlet /> provides undefined, and a destructuring const { settings } = useOutletContext() in the grandchild throws "Cannot destructure property of undefined". The next example lets you switch the forwarding on and off.

Context reaches only the next level

Open /orders/42. With the box unticked, the Orders layout has the context (it is a direct child of the Account layout) but the Order page sees undefined. Tick the box and the page receives {"user":"Ada"}. If you need a value several levels deep, forwarding at every level gets tedious, which is the first sign you want a different tool (see the end of this lesson).

Keep the value stable

<Outlet context={...}> is a context provider, and React re-renders every consumer whenever the provided value is a different object from the last render. If a layout writes context={{ settings, setSettings }} inline, it creates a new object each time the layout re-renders, even when nothing in it changed, and every child that calls useOutletContext() re-renders too. Wrap the value in useMemo (as the first examples did) so it only changes when its contents do.

Memoize the context value

With the box unticked, every click on the button makes a new { user: 'Ada' } object, and the child's render count goes up although nothing visible changed. Tick the box and click again: the same object is provided each time, so the count stays put. For a tiny child this is harmless, but with big pages below the layout it is worth the one useMemo line.

Typed helper hooks

In TypeScript, useOutletContext takes a type argument, but React Router cannot check that the layout really passes that type. A small wrapper keeps the type in one place and fails loudly when used in the wrong place:

TSX
// settings-context.ts - React Router (read-only)
import type { Dispatch, SetStateAction } from 'react';
import { useOutletContext } from 'react-router';

export type Settings = { name: string; theme: 'light' | 'dark' };
export type SettingsContext = {
  settings: Settings;
  setSettings: Dispatch<SetStateAction<Settings>>;
};

export function useSettings(): SettingsContext {
  const context = useOutletContext<SettingsContext | undefined>();
  if (!context) {
    throw new Error('useSettings must be used inside a route rendered by SettingsLayout');
  }
  return context;
}

Child pages then call useSettings() and never touch useOutletContext directly.

When not to use Outlet context

Outlet context is a convenient tool with a narrow job: UI state owned by a layout and consumed by its direct child routes. Pick something else in these cases:

  • The data comes from the server for this URL. In data mode, load it in a route loader and read it with useLoaderData() in the route itself, or with useRouteLoaderData('routeId') from any descendant. Loaders run before rendering, in parallel, and revalidate after mutations; see Loaders: Data Before Render.
  • The value is needed at any depth. A normal React context provider wrapped around the layout's contents reaches every descendant without forwarding. Outlet context only goes one level.
  • The value is needed by components outside the router. A provider higher in the tree (or a store) works everywhere.
  • The value belongs in the address. Filters, tabs and page numbers are better as search params, so they can be shared and bookmarked.
flowchart TD
    Q["Shared value for child routes"] --> A{"Where does it come from?"}
    A -->|"Server data for the URL"| L["Route loader<br/>useLoaderData / useRouteLoaderData"]
    A -->|"State owned by a layout"| B{"Which components need it?"}
    A -->|"Part of the address"| U["URL params or search params"]
    B -->|"Direct child pages only"| O["Outlet context"]
    B -->|"Any depth or outside routes"| C["Your own React context provider"]

A quick way to pick the tool: server data goes in loaders, shareable state in the URL, and layout-owned UI state in Outlet context or a custom provider.

The stand-in examples here pass state only. Everything else in this track uses the same pattern of nested layouts, so the next lesson explains how links inside them are resolved: Relative Links and Relative Routing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a child route read the value its layout passed with <Outlet context={value} />?

    The router renders the child itself, so you cannot pass props. useOutletContext() returns the value given to the Outlet that rendered the current route.
  2. 2. A layout passes context to its Outlet. A child layout renders another <Outlet /> without a context prop. What does the grandchild route get from useOutletContext()?

    Each Outlet provides the value to the route it renders. A middle layout must forward it with <Outlet context={useOutletContext()} /> (or build a new value).
  3. 3. Why should you wrap a context object in useMemo before passing it to Outlet?

    Context consumers re-render when the provided value is a different object. useMemo keeps the same object until its dependencies change.
  4. 4. Product data is fetched from an API for the current URL, and several nested pages need it. Which tool is the best fit in data mode?

    Loaders fetch data for a route before it renders, run nested loaders in parallel and revalidate after mutations. Outlet context is meant for UI state owned by a layout.

Summary

  • A layout passes a value with <Outlet context={value} />, and its child routes read it with useOutletContext().
  • Include setter functions in the value so pages can change layout-owned state.
  • Context reaches only the route rendered by that Outlet; middle layouts must forward it with <Outlet context={useOutletContext()} />.
  • Memoize the value with useMemo so consumers do not re-render needlessly.
  • In TypeScript, wrap useOutletContext in a typed helper hook that throws when the context is missing.
  • Use loaders for server data, the URL for shareable state, and a normal context provider when many levels or outside components need the value.

Next: Relative Links and Relative Routing