@@ -405,9 +405,76 @@ const OutletContext = React.createContext<unknown>(null);
405
405
/**
406
406
* Returns the parent route {@link Outlet | `<Outlet context>`}.
407
407
*
408
+ * Often parent routes manage state or other values you want shared with child
409
+ * routes. You can create your own [context provider](https://react.dev/learn/passing-data-deeply-with-context)
410
+ * if you like, but this is such a common situation that it's built-into
411
+ * `<Outlet />`.
412
+ *
413
+ * ```tsx
414
+ * // Parent route
415
+ * function Parent() {
416
+ * const [count, setCount] = React.useState(0);
417
+ * return <Outlet context={[count, setCount]} />;
418
+ * }
419
+ * ```
420
+ *
421
+ * ```tsx
422
+ * // Child route
423
+ * import { useOutletContext } from "react-router-dom";
424
+ *
425
+ * function Child() {
426
+ * const [count, setCount] = useOutletContext();
427
+ * const increment = () => setCount((c) => c + 1);
428
+ * return <button onClick={increment}>{count}</button>;
429
+ * }
430
+ * ```
431
+ *
432
+ * If you're using TypeScript, we recommend the parent component provide a custom
433
+ * hook for accessing the context value. This makes it easier for consumers to
434
+ * get nice typings, control consumers, and know who's consuming the context value.
435
+ *
436
+ * Here's a more realistic example:
437
+ *
438
+ * ```tsx filename=src/routes/dashboard.tsx lines=[13,19]
439
+ * import * as React from "react";
440
+ * import type { User } from "./types";
441
+ * import { Outlet, useOutletContext } from "react-router-dom";
442
+ *
443
+ * type ContextType = { user: User | null };
444
+ *
445
+ * export default function Dashboard() {
446
+ * const [user, setUser] = React.useState<User | null>(null);
447
+ *
448
+ * return (
449
+ * <div>
450
+ * <h1>Dashboard</h1>
451
+ * <Outlet context={{ user } satisfies ContextType} />
452
+ * </div>
453
+ * );
454
+ * }
455
+ *
456
+ * export function useUser() {
457
+ * return useOutletContext<ContextType>();
458
+ * }
459
+ * ```
460
+ *
461
+ * ```tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
462
+ * import { useUser } from "../dashboard";
463
+ *
464
+ * export default function DashboardMessages() {
465
+ * const { user } = useUser();
466
+ * return (
467
+ * <div>
468
+ * <h2>Messages</h2>
469
+ * <p>Hello, {user.name}!</p>
470
+ * </div>
471
+ * );
472
+ * }
473
+ * ```
474
+ *
408
475
* @public
409
476
* @category Hooks
410
- * @returns The context value passed to the {@link Outlet} component
477
+ * @returns The context value passed to the parent {@link Outlet} component
411
478
*/
412
479
export function useOutletContext < Context = unknown > ( ) : Context {
413
480
return React . useContext ( OutletContext ) as Context ;
0 commit comments