Created
May 5, 2021 20:32
-
-
Save tchak/f67715535fd6d9431a4cb8fda022d2e5 to your computer and use it in GitHub Desktop.
ClientOnly
This file contains hidden or 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
// 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