useIsomorphicLayoutEffect
Hook that uses useLayoutEffect on the client and useEffect on the server (for SSR compatibility).
Import
import { useIsomorphicLayoutEffect } from "amvasdev-ui";Signature
useIsomorphicLayoutEffect(effect, deps): voidParameters
| Name | Type | Required | Description |
|---|---|---|---|
| effect | () => void | (() => void) | Yes | Effect function to run |
| deps | DependencyList | No | Dependencies array |
Live Demo
Window Width Tracker
Resize your browser window to see the width update:
Width: 0px
Scroll Position Tracker
Scroll the page to see the position update:
Scroll Y: 0px
Examples
Responsive Component
import { useIsomorphicLayoutEffect } from "amvasdev-ui";
import { useState } from "react";
function ResponsiveComponent() {
const [width, setWidth] = useState(0);
useIsomorphicLayoutEffect(() => {
const updateWidth = () => setWidth(window.innerWidth);
updateWidth();
window.addEventListener("resize", updateWidth);
return () => window.removeEventListener("resize", updateWidth);
}, []);
return <div>Width: {width}px</div>;
}Scroll Position
import { useIsomorphicLayoutEffect } from "amvasdev-ui";
import { useState } from "react";
function ScrollIndicator() {
const [scrollY, setScrollY] = useState(0);
useIsomorphicLayoutEffect(() => {
const handleScroll = () => setScrollY(window.scrollY);
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return <div>Scroll position: {scrollY}px</div>;
}Notes
- Prevents SSR warnings when using layout effects
- Same API as useLayoutEffect
- Use this instead of useLayoutEffect for SSR-compatible code
This hook is essential for Next.js and other SSR frameworks. It prevents console warnings when using layout effects in server-side rendered components.