JAVASCRIPT
Safe `useLayoutEffect` for SSR/CSR with `useIsomorphicLayoutEffect`
Learn to use `useIsomorphicLayoutEffect`, a custom hook that conditionally uses `useLayoutEffect` or `useEffect` to safely handle DOM measurements in both client-side and server-side rendering.
import { useEffect, useLayoutEffect } from 'react';
const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect;
// Example Usage:
// function MyComponent() {
// const ref = useRef(null);
// useIsomorphicLayoutEffect(() => {
// if (ref.current) {
// // Perform DOM measurements or mutations here
// const height = ref.current.offsetHeight;
// console.log('Element height:', height);
// }
// }, []); // Run once on mount
// return <div ref={ref}>Hello Isomorphic</div>;
// }
How it works: `useIsomorphicLayoutEffect` is a custom hook designed to safely use the behavior of `useLayoutEffect` (which runs synchronously after all DOM mutations) in environments that support both client-side and server-side rendering (SSR). It conditionally assigns `useLayoutEffect` on the client (where `window` is defined) and `useEffect` on the server (where `window` is undefined), preventing potential errors during SSR while maintaining correct DOM measurement timing on the client.