Random UI

use-hydration

Utility hook to check if we're in client-side context

If you're using React, this hook is not required

This hook helps prevent hydration mismatches and client-side errors in server-rendered applications. When a component first renders on the server, client-only APIs like window, document, localStorage, or browser-specific APIs are not available.

The useHydration hook returns false during the initial server render and first client render, then returns true after the component has mounted on the client (via useEffect). This allows you to conditionally render client-only code only after hydration is complete, preventing errors like "window is not defined" or "localStorage is not defined".

Installation

Copy and paste the following code into your project.

use-hydration.ts
"use client";
import { useEffect, useState } from "react";

/**
 * Hook to check if we're in client-side context
 * @returns {boolean} isMounted
 */
export const useHydration = (): boolean => {
  const [isMounted, setIsMounded] = useState(false);

  useEffect(() => {
    setIsMounded(true);
  }, []);

  return isMounted;
};

Usage

import { useHydration } from "@/hooks/use-hydration";
const isMounted = useHydration();

// remember: all hooks must be before return statement

if (!isMounted) return null;

return (
  // Component with client code
)

On this page