I recently discovered that you can retain data across nested routes using the <Outlet />
component. Here is an example:
//dash.tsx
import { Outlet, json, useLoaderData } from "@remix-run/react";
import { getSession } from "~/utils/session.server";
export async function loader({ request }) {
let session = await getSession(request.headers.get("Cookie"));
return json({ user: session.user });
}
export default function DashRoute() {
const { user } = useLoaderData();
return (
<main className="flex h-screen shadow w-full">
<Outlet context={user} />
</main>
);
}
//childView.tsx
import { useOutletContext } from "@remix-run/react";
function Child() {
const user = useOutletContext();
// ...
}
While this method allows the context to be accessible in nested routes, it does not enable data access within the loader
of these nested routes. For instance, if you need to fetch posts for a user, you still need to call the getSession() function separately. This approach might lead to inconsistencies if parameters vary across nested routes.
Is there a more consistent way to access data from the root route’s loader
in all nested routes? How can we avoid redundant calls to getSession() and ensure consistent parameters across nested routes?
Thank you!