Skip to content

Commit

Permalink
Use a ref to ensure this only happens once
Browse files Browse the repository at this point in the history
Even in strict mode, plus we don't have to disable the lint warning.
  • Loading branch information
RobinClowers committed Apr 26, 2023
1 parent 66cc556 commit e92a512
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions emotion/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
ScrollRestoration,
useCatch,
} from "@remix-run/react";
import { useContext, useEffect } from "react";
import { useContext, useEffect, useRef } from "react";

import ServerStyleContext from "./styles/server.context";
import ClientStyleContext from "./styles/client.context";
Expand All @@ -35,11 +35,15 @@ const Document = withEmotionCache(
({ children, title }: DocumentProps, emotionCache) => {
const serverStyleData = useContext(ServerStyleContext);
const clientStyleData = useContext(ClientStyleContext);
const reinjectStylesRef = useRef(true);

// Only executed on client
// When a top level ErrorBoundary or CatchBoundary are rendered,
// the document head gets removed, so we have to create the style tags
useEffect(() => {
if (!reinjectStylesRef.current) {
return;
}
// re-link sheet container
emotionCache.sheet.container = document.head;

Expand All @@ -52,9 +56,9 @@ const Document = withEmotionCache(

// reset cache to re-apply global styles
clientStyleData.reset();
// We only want to do this on mount, not when styles change
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// ensure we only do this once per mount
reinjectStylesRef.current = false;
}, [clientStyleData, emotionCache.sheet]);

return (
<html lang="en">
Expand Down

0 comments on commit e92a512

Please sign in to comment.