How to Update Outlet Component in React

This article explains how to dynamically update and share state with the Outlet component in React Router. You will learn how to use the context prop to pass data and state-updating functions from a parent layout route down to its nested child routes, ensuring seamless data updates across your application.

In React Router, the Outlet component is a placeholder that renders child route components. Because you do not render the child components directly inside the layout, you cannot pass standard React props to them. To solve this and update nested routes dynamically, React Router provides the context prop on the <Outlet /> and a corresponding useOutletContext hook for the child components.

Step 1: Pass State Through the Outlet Context

To update child components inside an Outlet, define your state in the parent layout component. Then, pass the state variable and its updater function into the Outlet component’s context prop.

import { useState } from "react";
import { Outlet } from "react-router-dom";

export default function DashboardLayout() {
  const [user, setUser] = useState({ name: "Alex", theme: "light" });

  return (
    <div className={`dashboard ${user.theme}`}>
      <header>
        <h1>Welcome, {user.name}</h1>
      </header>
      <main>
        {/* Pass the state and setter function as context */}
        <Outlet context={{ user, setUser }} />
      </main>
    </div>
  );
}

Step 2: Access and Update the State in Child Routes

In any child component rendered inside the Outlet, import the useOutletContext hook from react-router-dom. This hook retrieves the exact context object passed by the parent, allowing the child to read the state and trigger updates.

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

export default function SettingsPage() {
  // Retrieve the state and setter from the parent outlet
  const { user, setUser } = useOutletContext();

  const toggleTheme = () => {
    setUser((prevUser) => ({
      ...prevUser,
      theme: prevUser.theme === "light" ? "dark" : "light",
    }));
  };

  return (
    <div>
      <h2>Settings</h2>
      <p>Current Theme: {user.theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

Key Considerations