useIsomorphicLayoutEffect
Hooks

useIsomorphicLayoutEffect

useLayoutEffect on the client and useEffect on the server.

Signature

useLayoutEffect logs a warning when React renders on the server, because there is no layout to read. This hook resolves to useEffect on the server and useLayoutEffect in the browser, with the same signature as either.

SignatureTypeScript
const useIsomorphicLayoutEffect: (
  effect: EffectCallback,
  deps?: DependencyList,
) => void;

Usage

ExampleTSX
import { useRef, useState } from "react";
import { useIsomorphicLayoutEffect } from "@solarius/onset";

function Measured() {
  const ref = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);

  useIsomorphicLayoutEffect(() => {
    const element = ref.current;
    if (element) setWidth(element.getBoundingClientRect().width);
  }, []);

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