|
| 1 | +--- |
| 2 | +title: createContext |
| 3 | +unstable: true |
| 4 | +--- |
| 5 | + |
| 6 | +# unstable_createContext |
| 7 | + |
| 8 | +[MODES: framework, data] |
| 9 | + |
| 10 | +<br/> |
| 11 | +<br/> |
| 12 | + |
| 13 | +<docs-warning>This API is experimental and subject to breaking changes. Enable it with the `future.unstable_middleware` flag.</docs-warning> |
| 14 | + |
| 15 | +## Summary |
| 16 | + |
| 17 | +[Reference Documentation ↗](https://api.reactrouter.com/v7/functions/react_router.unstable_createContext.html) |
| 18 | + |
| 19 | +Creates a type-safe context object that can be used to store and retrieve values in middleware, loaders, and actions. Similar to React's `createContext`, but designed for React Router's request/response lifecycle. |
| 20 | + |
| 21 | +## Signature |
| 22 | + |
| 23 | +```tsx |
| 24 | +unstable_createContext<T>(defaultValue?: T): RouterContext<T> |
| 25 | +``` |
| 26 | + |
| 27 | +## Params |
| 28 | + |
| 29 | +### defaultValue |
| 30 | + |
| 31 | +An optional default value for the context. This value will be returned if no value has been set for this context. |
| 32 | + |
| 33 | +## Returns |
| 34 | + |
| 35 | +A `RouterContext<T>` object that can be used with `context.get()` and `context.set()` in middleware, loaders, and actions. |
| 36 | + |
| 37 | +## Examples |
| 38 | + |
| 39 | +### Basic Usage |
| 40 | + |
| 41 | +```tsx filename=app/context.ts |
| 42 | +import { unstable_createContext } from "react-router"; |
| 43 | + |
| 44 | +// Create a context for user data |
| 45 | +export const userContext = |
| 46 | + unstable_createContext<User | null>(null); |
| 47 | +``` |
| 48 | + |
| 49 | +```tsx filename=app/middleware/auth.ts |
| 50 | +import { userContext } from "~/context"; |
| 51 | +import { getUserFromSession } from "~/auth.server"; |
| 52 | + |
| 53 | +export const authMiddleware = async ({ |
| 54 | + request, |
| 55 | + context, |
| 56 | +}) => { |
| 57 | + const user = await getUserFromSession(request); |
| 58 | + context.set(userContext, user); |
| 59 | +}; |
| 60 | +``` |
| 61 | + |
| 62 | +```tsx filename=app/routes/profile.tsx |
| 63 | +import { userContext } from "~/context"; |
| 64 | + |
| 65 | +export async function loader({ |
| 66 | + context, |
| 67 | +}: Route.LoaderArgs) { |
| 68 | + const user = context.get(userContext); |
| 69 | + |
| 70 | + if (!user) { |
| 71 | + throw new Response("Unauthorized", { status: 401 }); |
| 72 | + } |
| 73 | + |
| 74 | + return { user }; |
| 75 | +} |
| 76 | +``` |
| 77 | + |
| 78 | +## See Also |
| 79 | + |
| 80 | +- [Middleware Guide](../../how-to/middleware) |
0 commit comments