Kosorikōsori alpha

useIsomorphicLayoutEffect

Uses `useLayoutEffect` in SSR and `useEffect` in CSR.

Check the console

Installation

Copy-paste the hook

Copy and paste the hook code in a .ts file.

import { useEffect, useLayoutEffect } from 'react';
 
/**
 * A custom hook that uses `useLayoutEffect` on the client and `useEffect` on the server.
 *
 * @param {React.EffectCallback} [effect] - The function that contains the side-effect logic.
 * @param {React.DependencyList} [deps] - An optional array of dependencies that, when changed, will re-run the effect.
 *
 * @returns `void`
 *
 * @example
 * import { useIsomorphicLayoutEffect } from '~/hooks/use-isomorphic-layout-effect';
 * useIsomorphicLayoutEffect(() => {
 *   console.log(
 *     "In the browser, I'm an `useLayoutEffect`, but in SSR, I'm an `useEffect`.",
 *   );
 * }, []);
 */
export const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect;

Usage

import { useIsomorphicLayoutEffect } from '~/hooks/use-isomorphic-layout-effect';
useIsomorphicLayoutEffect(() => {
  console.log(
    "In the browser, I'm an `useLayoutEffect`, but in SSR, I'm an `useEffect`.",
  );
}, []);

Details

Isomorphic behavior

  • useIsomorphicLayoutEffect ensures that useLayoutEffect is only used in client-side rendering (CSR) environments where the DOM is available. In server-side rendering (SSR), it safely falls back to useEffect to prevent React warnings.
  • This behavior helps avoid issues with server-side rendering since useLayoutEffect runs synchronously after all DOM mutations and can’t be used on the server where there’s no DOM.

Synchronous vs Asynchronous effects

  • On the client, the hook behaves like useLayoutEffect, meaning it runs synchronously after all DOM changes but before the browser has a chance to paint. This is useful for tasks like measuring layout, handling scroll positions, or making DOM manipulations.
  • On the server, it behaves like useEffect, which is asynchronous and won’t block rendering. This allows the server to execute logic safely without worrying about DOM access.

On this page