1

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

  • 1
    Have you tried adding a check to make sure `scroll` is defined before calling `scroll.destroy()`? E.g. `if (scroll) scroll.destroy();`. – juliomalves Jun 08 '22 at 22:58

2 Answers2

2

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 to scroll variable with some delay. Unfortunately, your cleanup is called before that, so scroll is undefined. 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

Aitwar
  • 839
  • 4
  • 11
0

As far as I find out then React vs18 useEffect auto run cleanup. You can find it at React18

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 09 '22 at 03:33