Created
July 12, 2024 14:49
-
-
Save danieljpgo/1b0a60e6c79768a0e2e40d9e42c66d7f to your computer and use it in GitHub Desktop.
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 { useHydrated } from "~/hooks/use-hydrated"; | |
export function ClientOnly({ children }: React.PropsWithChildren) { | |
const hydrated = useHydrated(); | |
return hydrated ? children : null; | |
} |
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
import * as React from "react"; | |
function subscribe() { | |
return () => {}; | |
} | |
/** | |
* Return a boolean indicating if the JS has been hydrated already. | |
* When doing Server-Side Rendering, the result will always be false. | |
* When doing Client-Side Rendering, the result will always be false on the | |
* first render and true from then on. Even if a new component renders it will | |
* always start with true. | |
* | |
* Example: Disable a button that needs JS to work. | |
* ```tsx | |
* let hydrated = useHydrated(); | |
* return ( | |
* <button type="button" disabled={!hydrated} onClick={doSomethingCustom}> | |
* Click me | |
* </button> | |
* ); | |
* ``` | |
*/ | |
export function useHydrated() { | |
return React.useSyncExternalStore( | |
subscribe, | |
() => true, | |
() => false, | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment