Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix chakra-ui hydration issue #430

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions chakra-ui/app/clientContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { createContext } from "react";

export interface ClientStyleContextData {
reset: () => void;
}

export const ClientStyleContext = createContext<ClientStyleContextData | null>(
null,
);
50 changes: 41 additions & 9 deletions chakra-ui/app/entry.client.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,60 @@
import createEmotionCache from "@emotion/cache";
import { CacheProvider } from "@emotion/react";
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { startTransition, StrictMode, useCallback, useState } from "react";
import { hydrate } from "react-dom";
import { ClientStyleContext } from "./clientContext";

const hydrate = () => {
function ClientCacheProvider({ children }: { children: React.ReactNode }) {
const [cache, setCache] = useState(createEmotionCache({ key: "css" }));

const reset = useCallback(() => {
return setCache(createEmotionCache({ key: "css" }));
}, []);

return (
<ClientStyleContext.Provider value={{ reset }}>
<CacheProvider value={cache}>{children}</CacheProvider>
</ClientStyleContext.Provider>
);
}

const hydration = () => {
const emotionCache = createEmotionCache({ key: "css" });

startTransition(() => {
hydrateRoot(
document,
/*
why `hydrate`? When using `HydrateRoot`, the deferred data, that is fast, will flash on the screen to the fallback during hydration.
I've fixed flashing fast deferred data this by using `hydrate` instead and it works.
If you don't defer any data you may use `HydrateRoot` instead, since it's newer.

You can change to `HydrateRoot`, to see the flash of "medium data" on index page.
The flash will be more noticable, when the app grows, and hydration takes longer.

hydrateRoot(
document,
<StrictMode>
<ClientCacheProvider>
<RemixBrowser />
</ClientCacheProvider>
</StrictMode>,
);
*/
hydrate(
<StrictMode>
<CacheProvider value={emotionCache}>
<ClientCacheProvider>
<RemixBrowser />
</CacheProvider>
</ClientCacheProvider>
</StrictMode>,
document,
);
});
};

if (typeof requestIdleCallback === "function") {
requestIdleCallback(hydrate);
requestIdleCallback(hydration);
} else {
// Safari doesn't support requestIdleCallback
// https://caniuse.com/requestidlecallback
setTimeout(hydrate, 1);
setTimeout(hydration, 1);
}
37 changes: 18 additions & 19 deletions chakra-ui/app/root.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChakraProvider, Box, Heading } from "@chakra-ui/react";
import { Box, ChakraProvider, Heading } from "@chakra-ui/react";
import type { MetaFunction } from "@remix-run/node";
import {
Links,
Expand All @@ -7,8 +7,9 @@ import {
Outlet,
Scripts,
ScrollRestoration,
useCatch,
} from "@remix-run/react";
import { useContext, useLayoutEffect, useRef } from "react";
import { ClientStyleContext } from "./clientContext";

export const meta: MetaFunction = () => ({
charset: "utf-8",
Expand All @@ -22,6 +23,21 @@ function Document({
children: React.ReactNode;
title?: string;
}) {
const clientStyleData = useContext(ClientStyleContext);
const reinjectStylesRef = useRef(true);

/*
We do `useLayoutEffect`, to render the emotion styles, before browser paints the screen.
And we want to make sure, we only do this once, when the component mounts.
*/
useLayoutEffect(() => {
if (!reinjectStylesRef.current) return;

clientStyleData?.reset();

reinjectStylesRef.current = false;
}, []);

return (
<html lang="en">
<head>
Expand Down Expand Up @@ -51,23 +67,6 @@ export default function App() {
);
}

// How ChakraProvider should be used on CatchBoundary
export function CatchBoundary() {
const caught = useCatch();

return (
<Document title={`${caught.status} ${caught.statusText}`}>
<ChakraProvider>
<Box>
<Heading as="h1" bg="purple.600">
[CatchBoundary]: {caught.status} {caught.statusText}
</Heading>
</Box>
</ChakraProvider>
</Document>
);
}

// How ChakraProvider should be used on ErrorBoundary
export function ErrorBoundary({ error }: { error: Error }) {
return (
Expand Down
40 changes: 39 additions & 1 deletion chakra-ui/app/routes/_index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,47 @@
import { Box } from "@chakra-ui/react";
import { Box, Text } from "@chakra-ui/react";
import { defer, type LoaderArgs } from "@remix-run/node";
import { Await, useLoaderData } from "@remix-run/react";
import { Suspense } from "react";

export async function loader(_: LoaderArgs) {
const slowData = new Promise((resolve) => {
setTimeout(() => {
resolve("slow data");
}, 1000);
});

const mediumData = new Promise((resolve) => {
setTimeout(() => {
resolve("medium data");
}, 150);
});

const instantData = "instant data";

return defer({
instantData,
mediumData,
slowData,
});
}

export default function Index() {
const { instantData, mediumData, slowData } = useLoaderData<typeof loader>();

return (
<Box bg="tomato" w="100%" p={4} color="white">
Hello World!
<Text>{instantData}</Text>
<Suspense
fallback={<Text color={"yellow.100"}>Loading Medium data...</Text>}
>
<Await resolve={mediumData}>{(data) => <Text>{data}</Text>}</Await>
</Suspense>
<Suspense
fallback={<Text color={"yellow.100"}>Loading Slow data...</Text>}
>
<Await resolve={slowData}>{(data) => <Text>{data}</Text>}</Await>
</Suspense>
</Box>
);
}