How toAccess React Router's Loaders Data in entry.client

If you need to run some code in app/entry.client.tsx before hydrating your React Router application, you can leverage the global window.__reactRouterContext object to access the data.

First return the data you need from a route loader, e.g from app/root.tsx.

app/root.tsx
export async function loader() { let env = { GA_ID: process.env.GA_ID! }; return data({ env }) } // more code

Then in your entry.client you can access it.

app/entry.client.tsx
import { HydratedRouter } from "react-router"; import { startTransition, StrictMode } from "react"; import { hydrateRoot } from "react-dom/client"; const { GA_ID } = window.__reactRouterContext.state.loaderData.root.env; // use value here startTransition(() => { hydrateRoot( document, <StrictMode> <HydratedRouter /> </StrictMode> ); });