Skip to content

useIsomorphicLayoutEffect

useLayoutEffect in the browser and useEffect on the server.

useLayoutEffect in the browser and useEffect on the server.

Import

import { useIsomorphicLayoutEffect } from '@kamod-ch/hooks'

Live demo

Basic demo

useLayoutEffect in the browser and useEffect on the server.

Measured width after mount: 0

import { useState } from 'preact/hooks'
import { useIsomorphicLayoutEffect } from '@kamod-ch/hooks'

export default function UseIsomorphicLayoutEffectDemo() {
  const [width, setWidth] = useState(0)
  useIsomorphicLayoutEffect(() => {
    setWidth(window.innerWidth)
  }, [])
  return <p><strong>Measured width after mount:</strong> {width}</p>
}

API

TypeScript signature
import { useLayoutEffect } from 'preact/hooks';
declare const useIsomorphicLayoutEffect: typeof useLayoutEffect;
export default useIsomorphicLayoutEffect;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.