You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
292. ### How does useLayoutEffect work during server-side rendering (SSR)?
7035
+
7036
+
The `useLayoutEffect` hook does **not run on the server**, because there is no DOM. React issues a warning in server environments like Next.js if `useLayoutEffect` is used directly.
7037
+
7038
+
This can be mitigated using a conditional polyfill:
i.e, Use `useIsomorphicLayoutEffect` in components that render both on client and server.
7046
+
7047
+
**[⬆ Back to Top](#table-of-contents)**
7048
+
7049
+
293. ### What happens if you use useLayoutEffect for non-layout logic?
7050
+
Using `useLayoutEffect` for logic **unrelated to layout or visual DOM changes** (such as logging, data fetching, or analytics) is **not recommended**. It can lead to **performance issues** or even unexpected behavior.
7051
+
7052
+
**Example: Anti-pattern**
7053
+
```js
7054
+
useLayoutEffect(() => {
7055
+
console.log("Tracking analytics");
7056
+
fetch('/log-page-view');
7057
+
}, []);
7058
+
```
7059
+
The above usage delays the paint of the UI just to send a network request, which could (and should) be done after paint using useEffect.
7060
+
7061
+
**[⬆ Back to Top](#table-of-contents)**
7062
+
7063
+
294. ### How does useLayoutEffect cause layout thrashing?
7064
+
The `useLayoutEffect` can **cause layout thrashing** when you **repeatedly read and write to the DOM** in ways that force the browser to recalculate layout multiple times per frame. This is because `useLayoutEffect` runs _before the browser paints_, these reflows happen _synchronously_, blocking rendering and degrading performance.
0 commit comments