Skip to content

Instantly share code, notes, and snippets.

@RTAndrew
Created November 7, 2024 09:56
Show Gist options
  • Save RTAndrew/129b827fb621709c4a22a56eea6a60ee to your computer and use it in GitHub Desktop.
Save RTAndrew/129b827fb621709c4a22a56eea6a60ee to your computer and use it in GitHub Desktop.
StyledComponent Registry for Next.js 14+
"use client";
import React, { useState } from "react";
import { useServerInsertedHTML } from "next/navigation";
import { ServerStyleSheet, StyleSheetManager } from "styled-components";
type SSRStyledComponentRegistryProps = {
children: React.ReactNode;
};
/**
* Reduces (does not prevent) FOUC when using StyledComponents
* @description
* StyledComponents forces the "use client" directive in Next 14+,
* removing the SSR benefits and increasing style hydration
* @link https://medium.com/@felipe.nava/using-styled-components-in-nextjs-app-router-35295688e27a
*/
export const SSRStyledComponentRegistry = ({
children,
}: SSRStyledComponentRegistryProps) => {
const [styledComponentsStyleSheet] = useState(() => new ServerStyleSheet());
useServerInsertedHTML(() => {
const styles = styledComponentsStyleSheet.getStyleElement();
styledComponentsStyleSheet.instance.clearTag();
return <>{styles}</>;
});
if (typeof window !== "undefined") return <>{children}</>;
return (
<StyleSheetManager sheet={styledComponentsStyleSheet.instance}>
{children}
</StyleSheetManager>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment