A React hook that tells you when the client has hydrated, so you can avoid SSR mismatches in Next.js.
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".
Copy and paste the following code into your project.
"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;
};import { useHydration } from "@/hooks/use-hydration";const isMounted = useHydration();
// remember: all hooks must execute before return statement
if (!isMounted) return null;
return (
// Component with client code
)