Creates a type-safe unstable_RouterContext
object that can be used to
action
s,loader
s, and middleware.createContext
,future.unstable_middleware
flag.
If a defaultValue
is provided, it will be returned from context.get()
when no value has been set for the context. Otherwise, reading this context
when no value has been set will throw an error.
import { unstable_createContext } from "react-router";
// Create a context for user data
export const userContext =
unstable_createContext<User | null>(null);
import { getUserFromSession } from "~/auth.server";
import { userContext } from "~/context";
export const authMiddleware = async ({
context,
request,
}) => {
const user = await getUserFromSession(request);
context.set(userContext, user);
};
import { userContext } from "~/context";
export async function loader({
context,
}: Route.LoaderArgs) {
const user = context.get(userContext);
if (!user) {
throw new Response("Unauthorized", { status: 401 });
}
return { user };
}
function unstable_createContext<T>(
defaultValue?: T,
): unstable_RouterContext<T>
An optional default value for the context. This value will be returned if no value has been set for this context.
A unstable_RouterContext
object that can be used with
context.get()
and context.set()
in action
s,
loader
s, and middleware.