i'm using locomotive scroll with next.js, after react v18 my clean up stage is stopped working... Can someone explain why?
useEffect(() => {
let scroll;
import("locomotive-scroll").then((locomotiveModule) => {
scroll = new locomotiveModule.default({
el: document.querySelector("[data-scroll-container]"),
smooth: true,
});
});
return () => {
scroll.destroy();
}});
I have error "Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'destroy')"
*If I down install react to 17 version all working fine
React v18 has introduced new dev-mode check regarding
useEffect
idempotency. Your effects will be called once, then immediately destroyed and recreated again.In your case problem is
import
takes some time (network request must be made), so value is assigned toscroll
variable with some delay. Unfortunately, your cleanup is called before that, soscroll
isundefined
. It's kind of race condition and it would also occur in React v17, but less frequently as it depends on several characteristics (CPU power, network speed).For details see this document: https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-strict-mode