@@ -24,6 +24,73 @@ https://github.com/remix-run/react-router/blob/main/packages/react-router/lib/ho
24
24
25
25
Returns the parent route [ ` <Outlet context> ` ] ( ../components/Outlet ) .
26
26
27
+ Often parent routes manage state or other values you want shared with child
28
+ routes. You can create your own [ context provider] ( https://react.dev/learn/passing-data-deeply-with-context )
29
+ if you like, but this is such a common situation that it's built-into
30
+ ` <Outlet /> ` .
31
+
32
+ ``` tsx
33
+ // Parent route
34
+ function Parent() {
35
+ const [count, setCount] = React .useState (0 );
36
+ return <Outlet context = { [count , setCount ]} />;
37
+ }
38
+ ```
39
+
40
+ ``` tsx
41
+ // Child route
42
+ import { useOutletContext } from " react-router-dom" ;
43
+
44
+ function Child() {
45
+ const [count, setCount] = useOutletContext ();
46
+ const increment = () => setCount ((c ) => c + 1 );
47
+ return <button onClick = { increment } >{ count } </button >;
48
+ }
49
+ ```
50
+
51
+ If you're using TypeScript, we recommend the parent component provide a custom
52
+ hook for accessing the context value. This makes it easier for consumers to
53
+ get nice typings, control consumers, and know who's consuming the context value.
54
+
55
+ Here's a more realistic example:
56
+
57
+ ``` tsx filename=src/routes/dashboard.tsx lines=[13,19]
58
+ import * as React from " react" ;
59
+ import type { User } from " ./types" ;
60
+ import { Outlet , useOutletContext } from " react-router-dom" ;
61
+
62
+ type ContextType = { user: User | null };
63
+
64
+ export default function Dashboard() {
65
+ const [user, setUser] = React .useState <User | null >(null );
66
+
67
+ return (
68
+ <div >
69
+ <h1 >Dashboard</h1 >
70
+ <Outlet context = { { user } satisfies ContextType } />
71
+ </div >
72
+ );
73
+ }
74
+
75
+ export function useUser() {
76
+ return useOutletContext <ContextType >();
77
+ }
78
+ ```
79
+
80
+ ``` tsx filename=src/routes/dashboard/messages.tsx lines=[1,4]
81
+ import { useUser } from " ../dashboard" ;
82
+
83
+ export default function DashboardMessages() {
84
+ const { user } = useUser ();
85
+ return (
86
+ <div >
87
+ <h2 >Messages</h2 >
88
+ <p >Hello, { user .name } !</p >
89
+ </div >
90
+ );
91
+ }
92
+ ```
93
+
27
94
## Signature
28
95
29
96
``` tsx
@@ -32,5 +99,5 @@ function useOutletContext<Context = unknown>(): Context
32
99
33
100
## Returns
34
101
35
- The context value passed to the [` Outlet ` ](../ components / Outlet ) component
102
+ The context value passed to the parent [` Outlet ` ](../ components / Outlet ) component
36
103
0 commit comments