useIsomorphicLayoutEffect
The useIsomorphicLayoutEffect hook is useLayoutEffect in the browser and useEffect on the server. It lets you measure or mutate the DOM synchronously before paint without React's "useLayoutEffect does nothing on the server" warning during server-side rendering.
Usage
Installation
import { useIsomorphicLayoutEffect } from "hookstorm";
Parameters
It takes the same parameters as useEffect:
- effect — The effect callback. It may return a cleanup function.
- deps — (optional) The dependency list.
Return Values
This hook does not return anything.
Example Usage
import { ReactElement, useRef, useState } from "react";
import { useIsomorphicLayoutEffect } from "hookstorm";
export default function Measured(): ReactElement {
const ref = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
// Runs before paint in the browser, so there is no visible flicker
useIsomorphicLayoutEffect(() => {
setHeight(ref.current?.offsetHeight ?? 0);
}, []);
return <div ref={ref}>Height: {height}px</div>;
}
Notes
- Use it in Next.js, Remix, or any other SSR setup instead of
useLayoutEffect. - On the client it behaves exactly like
useLayoutEffect, so keep the work inside it small.