Created
November 7, 2024 09:56
-
-
Save RTAndrew/129b827fb621709c4a22a56eea6a60ee to your computer and use it in GitHub Desktop.
StyledComponent Registry for Next.js 14+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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