Shadcn Hooks

useIsHydrated

A hook to check if the component is hydrated

useHydrated

npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-hydrated.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-hydrated.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-hydrated.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-is-hydrated.json"

Copy and paste the following code into your project.

use-is-hydrated.ts
import { useSyncExternalStore } 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 useIsHydrated() {
  return useSyncExternalStore(
    subscribe,
    () => true,
    () => false,
  )
}

credits

Last updated on

On this page