今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

React useIsomorphicLayoutEffect: Fix the SSR useLayoutEffect Warning (2026)

reactuse.com 2026年06月25日 11:22 3 次阅读 来源:Dev.to

You added a useLayoutEffect to measure a tooltip, shipped it, and the next time your Next.js (or Remix, or Gatsby) dev server rendered a page on the server, the console lit up: Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. The warning is correct, the suggested fix ("only use it on the client") is unhelpful, and the obvious workaround — just switch to useEffect — quietly reintroduces the visual bug you used useLayoutEffect to kill in the first place. useIsomorphicLayoutEffect is the small hook that resolves the standoff. This post explains exactly why the warning happens, why the two naive fixes are both wrong, and what the one-line hook actually does. Why useLayoutEffect Exists At All React gives you two effect hooks that look nearly identical: useEffect runs after the browser has painted. Its callback is queued and fires asynchronously once the frame is on screen. useLayoutEffect runs before the browser paints, synchronously, right after React has mutated the DOM but before the user sees anything. That timing difference is the whole point. If you need to read layout — getBoundingClientRect , scrollHeight , the measured width of a node — and then write a style based on it, you have to do it before paint. Otherwise the user sees one frame of the wrong layout, then a flicker as your useEffect corrects it. The canonical example is a tooltip that has to position itself relative to its own measured size: function Tooltip ({ targetRect , children }) { const ref = useRef < HTMLDivElement > ( null ); const [ pos , setPos ] = useState ({ top : 0 , left : 0 }); useLayoutEffect (() => { const { height , width } = ref . current ! . getBoundingClientRect (); // place the tooltip above the target, centered s

本文内容来源于互联网,版权归原作者所有
查看原文