useIsomorphicEffect
Uses a layout effect in the browser and a passive effect during server rendering.
About
useIsomorphicEffect is selected when the module loads: it is useLayoutEffect when window exists and useEffect otherwise. Use it for layout-sensitive client work in code that can also be imported by a server renderer.
Examples
import { useRef, useState } from "react";
import { useIsomorphicEffect } from "rooks";
export default function MeasuredLabel() {
const ref = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState(0);
useIsomorphicEffect(() => {
setWidth(ref.current?.getBoundingClientRect().width ?? 0);
}, []);
return <span ref={ref}>Measured width: {Math.round(width)}px</span>;
}Parameters
It accepts the same effect callback and optional dependency list as React's useEffect and useLayoutEffect. The effect may return a cleanup function.
Return value
The hook returns void.
Behavior and lifecycle
In a browser bundle, setup runs synchronously after DOM mutations and before paint; cleanup runs before changed setup and on unmount. On the server-selected path it has passive-effect semantics and does not execute during HTML rendering. Dependency comparison and error propagation are React's own.
Because selection happens at module evaluation, changing window later does not switch an already imported binding.
Compatibility and accessibility
The hook avoids the server warning associated with useLayoutEffect, but it does not make browser-only code safe: access DOM globals only inside the effect. Keep layout work short to avoid blocking paint, and avoid visual measurement that causes content to jump after hydration.