Skip to content

Instantly share code, notes, and snippets.

@tchak
Created May 5, 2021 20:32
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 tchak/f67715535fd6d9431a4cb8fda022d2e5 to your computer and use it in GitHub Desktop.
Save tchak/f67715535fd6d9431a4cb8fda022d2e5 to your computer and use it in GitHub Desktop.
ClientOnly
// global hydrating so future components don't do this dance, they just render
let hydrating = true;
// Component that renders `null` on the server and the initial browser render
// (while it's "hydrating")
function ClientOnly({ children }) {
// set initial state to whatever the global hydrating is, so once the app is
// hydrated, these components just render, no dance
let [hydrated, setHydrated] = useState(() => !hydrating);
// after hydration, rerender
useEffect(() => {
hydrating = false;
setHydrated(true);
}, []);
// only render if hydrated
return hydrated ? children : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment