Эх сурвалжийг харах

fix: use useLayoutEffect to eliminate layout shift on all devices

- Set correct width synchronously before browser paint via useLayoutEffect
- Desktop: no blank period, SSR content visible immediately with instant adjustment
- Mobile: CSS media query hides SSR layout, first paint shows correct layout with fade-in
- Separate resize listener into useEffect (only needed for ongoing resizes)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
rriecc 9 сар өмнө
parent
commit
5ac0f08f4b

+ 8 - 11
hooks/useWindowWidth.ts

@@ -1,4 +1,4 @@
-import { useState, useEffect } from "react";
+import { useState, useEffect, useLayoutEffect } from "react";
 
 // Default to 1280 (max container width) for SSR so server renders meaningful HTML
 const SSR_DEFAULT_WIDTH = 1280;
@@ -7,21 +7,18 @@ function useWindowWidth(): { width: number; settled: boolean } {
   const [width, setWidth] = useState<number>(SSR_DEFAULT_WIDTH);
   const [settled, setSettled] = useState(false);
 
+  // useLayoutEffect runs synchronously BEFORE browser paint,
+  // so the user never sees the SSR layout with wrong width
+  useLayoutEffect(() => {
+    setWidth(Math.min(window.innerWidth, 1280));
+    setSettled(true);
+  }, []);
+
   useEffect(() => {
     const handleResize = () => {
       setWidth(Math.min(window.innerWidth, 1280));
     };
 
-    // Set correct width immediately
-    handleResize();
-
-    // Wait for the layout to paint with the correct width, then reveal
-    requestAnimationFrame(() => {
-      requestAnimationFrame(() => {
-        setSettled(true);
-      });
-    });
-
     window.addEventListener("resize", handleResize);
 
     return () => window.removeEventListener("resize", handleResize);

+ 10 - 8
styles/globals.css

@@ -39,18 +39,20 @@
   transition-duration: 400ms;
 }
 
-/* Hide grid and disable item transitions until layout settles with correct width */
-.layout-initializing {
-  opacity: 0;
-}
-
+/* Disable grid item transitions during initial layout to prevent visible repositioning */
 .layout-initializing .react-grid-item {
   transition: none !important;
 }
 
-/* Fade in smoothly once layout is correct */
-.layout-settled {
-  animation: fade 0.4s ease-out;
+/* Mobile: hide layout until correct width is applied, then fade in */
+@media (max-width: 768px) {
+  .layout-initializing {
+    opacity: 0;
+  }
+
+  .layout-settled {
+    animation: fade 0.3s ease-out;
+  }
 }
 
 .react-grid-item > .react-resizable-handle {