Skip to content

Instantly share code, notes, and snippets.

@rossipedia
Last active January 22, 2024 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossipedia/7293cbd4958556b00fe7c62157c58fb9 to your computer and use it in GitHub Desktop.
Save rossipedia/7293cbd4958556b00fe7c62157c58fb9 to your computer and use it in GitHub Desktop.
...
renderToPipeableStream(
<HandoffProvider value={{ htmlClasses: 'dark' }}>
<RemixServer
context={remixContext}
url={request.url}
abortDelay={ABORT_DELAY}
/>
</HandoffProvider>,
{ ... }
);
...
import stableStringify from 'fast-json-stable-stringify';
import { createContext, useContext } from 'react';
import invariant from 'tiny-invariant';
interface HandoffData {
htmlClasses: string;
}
declare global {
interface Window {
__handoff: HandoffData;
}
}
const HandoffContext = createContext<HandoffData | undefined>(
typeof window !== 'undefined' && window.__handoff
? window.__handoff
: undefined
);
export const HandoffProvider = HandoffContext.Provider;
export function Handoff() {
const data = useHandoff();
const escapedJson = stableStringify(data).replace(/\\/g, '\\\\');
const script = `window.__handoff = JSON.parse('${escapedJson}');`;
return <script dangerouslySetInnerHTML={{ __html: script }} />;
}
export function useHandoff(): HandoffData {
const data = useContext(HandoffContext);
invariant(data, 'No handoff data found.');
return data;
}
import {
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from '@remix-run/react';
import { Handoff, useHandoff } from './handoff';
export default function App() {
const { htmlClasses } = useHandoff();
return (
<html lang="en" className={htmlClasses}>
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
<Handoff />
</head>
<body>
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment