useIsomorphicLayoutEffect
A `useLayoutEffect` equivalent that works safely in both client-side and server-side rendering environments.
Code
1import { useEffect, useLayoutEffect } from "react"
2
3export const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect
Usage Example
import { useState, useRef } from "react"
import { useIsomorphicLayoutEffect } from "@/hooks/use-isomorphic-layout-effect"
import { Button } from "@/components/ui/button"
export function IsomorphicLayoutEffectExample() {
const [width, setWidth] = useState(0)
const divRef = useRef<HTMLDivElement>(null)
useIsomorphicLayoutEffect(() => {
if (divRef.current) {
setWidth(divRef.current.offsetWidth)
}
}, [divRef.current]) // Recalculate if divRef.current changes
return (
<div className="space-y-4">
<div ref={divRef} className="w-full bg-npui-secondary p-4 rounded-md">
<p>This div's width is: {width}px</p>
</div>
<p className="text-sm text-npui-muted-foreground">
`useIsomorphicLayoutEffect` ensures this calculation runs correctly on both server and client.
</p>
</div>
)
}