Skip to content

Commit c98598f

Browse files
authored
Update useOutletContext.md with detailed information and example (#13982)
1 parent 85e7537 commit c98598f

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

contributors.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -412,3 +412,4 @@
412412
- zeromask1337
413413
- zheng-chuang
414414
- zxTomw
415+
- ioNihal

docs/api/hooks/useOutletContext.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,71 @@ Returns the parent route `<Outlet context>`.
2020
useOutletContext(): Context
2121
```
2222

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

0 commit comments

Comments
 (0)