Effects

useIsomorphicLayoutEffect

useLayoutEffect on the client, useEffect on the server.

Demo

target
50%
measured
0 px

Usage

use-isomorphic-layout-effect.tsxtsx
import { useRef, useState } from "react";
import { useIsomorphicLayoutEffect } from "hookli";

export function Demo() {
  const boxRef = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);

  useIsomorphicLayoutEffect(() => {
    setWidth(boxRef.current?.offsetWidth ?? 0);
  }, []);

  return <div ref={boxRef}>Measured: {width}px</div>;
}

API

useIsomorphicLayoutEffect.d.tsts
useIsomorphicLayoutEffect(effect: EffectCallback, deps?: DependencyList): void

Parameters

NameTypeDefaultDescription
effectEffectCallbackThe effect to run — same contract as React's useLayoutEffect, including an optional cleanup return.
depsDependencyListDependency array controlling when the effect re-runs. Omit to run after every render.

Returns

This hook returns nothing.

Hook

The implementation, straight from hookli. Copy it, or install the package.

src/hooks/use-isomorphic-layout-effect/use-isomorphic-layout-effect.tstsx
import { useEffect, useLayoutEffect } from "react";

/**
 * useLayoutEffect that safely falls back to useEffect on the server, where
 * useLayoutEffect would warn. Picks the layout effect only when a DOM exists.
 */
export const useIsomorphicLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;

View source on GitHub

Related hooks