typescriptbeginner

useIsomorphicLayoutEffect Hook

Safely uses useLayoutEffect on client and useEffect on server to avoid SSR warnings.

typescript
import { useEffect, useLayoutEffect } from 'react';

/**
 * useLayoutEffect on the client, useEffect on the server.
 * Prevents the 'useLayoutEffect does nothing on the server' warning.
 */
export const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect;

// Usage:
// useIsomorphicLayoutEffect(() => {
//   // Measure DOM, set initial positions, etc.
//   const rect = ref.current?.getBoundingClientRect();
//   setSize({ width: rect?.width ?? 0, height: rect?.height ?? 0 });
// }, []);

Use Cases

  • DOM measurement before paint
  • SSR-safe layout effects

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.