useEffect cleanup in React 18

2.6k views Asked by At

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

2

There are 2 answers

0
Aitwar On BEST ANSWER

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

1
Peter Nguyen On

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