useIsomorphicLayoutEffect
A custom React hook that behaves like useLayoutEffect on the client and useEffect on the server
useIsomorphicLayoutEffect selects useLayoutEffect in the browser and falls back to useEffect during server rendering.
It is useful for libraries that need layout timing in a browser but must avoid the server-rendering warning caused by calling useLayoutEffect during SSR.
Installation
CLI
npx shadcn add https://ui.tiesen.id.vn/r/use-isomorphic-layout-effect.jsonManual
Copy and paste the following code into your project.
import { useEffect, useLayoutEffect } from 'react'export const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffectUsage
import { useIsomorphicLayoutEffect } from '@/hooks/use-isomorphic-layout-effect'
export function Measure() {
useIsomorphicLayoutEffect(() => {
// Read or update browser layout state.
}, [])
return null
}Server rendering
The selection happens when the module is evaluated:
const useIsomorphicLayoutEffect =
typeof window === 'undefined' ? useEffect : useLayoutEffectOn the server it behaves exactly like useEffect; in the browser it uses useLayoutEffect.
API Reference
useIsomorphicLayoutEffect
The export is an alias with the same signature as React's effects:
const useIsomorphicLayoutEffect: typeof useEffect | typeof useLayoutEffectUse it exactly as you would use useLayoutEffect.