简体   繁体   中英

NextJs / Framer Motion: When using useViewportScroll I got this warning: Warning: useLayoutEffect does nothing on the server,

I am using NextJs with Framer Motion. Everything is working properly but I got this warning:

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.

Seems like this will be get fixed in the upcoming framer-motion version.

From the GitHub conversation

The React 18 upgrade in #1438 introduced a new useIsMounted hook, that that didn't use the useIsomorphicLayoutEffect. This resulted in a warning rendered serverside. Fix by replacing useLayoutEffect with useIsomprohicLayoutEffect

https://github.com/framer/motion/pull/1452

For a temporary fix, you can cancel rendering the the component if it is not client render, by adding such as

const [isLoaded, setLoaded] = useState(false);
useEffect(() => {
  setLoaded(true);
}, []);

if (!isLoaded) {
  return null;
}

return (
  ...your component
);

Next does SSR which is why its throwing this warning as useLayoutEffect doesn't run on server.

Official docs of useLayoutEffect :

The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM