Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Created July 12, 2024 14:49
Show Gist options
  • Save danieljpgo/1b0a60e6c79768a0e2e40d9e42c66d7f to your computer and use it in GitHub Desktop.
Save danieljpgo/1b0a60e6c79768a0e2e40d9e42c66d7f to your computer and use it in GitHub Desktop.
"use client";
import { useHydrated } from "~/hooks/use-hydrated";
export function ClientOnly({ children }: React.PropsWithChildren) {
const hydrated = useHydrated();
return hydrated ? children : null;
}
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