Effects
useIsomorphicLayoutEffect
useLayoutEffect on the client, useEffect on the server.
Demo
live · imported from hookli
- target
- 50%
- measured
- 0 px
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>;
}Usage
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(effect: EffectCallback, deps?: DependencyList): voidParameters
| Name | Type | Default | Description |
|---|---|---|---|
| effect | EffectCallback | — | The effect to run — same contract as React's useLayoutEffect, including an optional cleanup return. |
| deps | DependencyList | — | Dependency 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.
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;