jscottsmith / react-scroll-parallax

🔮 React hooks and components to create parallax scroll effects for banners, images or any other DOM elements.
https://react-scroll-parallax.damnthat.tv/
MIT License
2.9k stars 158 forks source link

fix: strict mode and missing context value #234

Closed raRaRa closed 1 year ago

raRaRa commented 1 year ago

This PR fixes #233 #227 and #221

The issue was that the controller could become null in between renders, e.g. when React is in strict mode. Strict mode in React makes all useEffects run twice, to make sure they don't have any memory leaks, etc. More can be read here: https://legacy.reactjs.org/docs/strict-mode.html#ensuring-reusable-state

What happened is that the last useEffect that handles unmount got called twice, thus the controller became null. This is not a NextJS issue, but React Strict mode issue (strict mode with useEffect came in React 18). Because of this, the useEffect should always handle both mount & unmount (never assume that unmount gets called once).

With this PR I never make the controller null, instead I just disable the controller which should clean all the event listeners. Please correct me if I'm wrong.

I've tested these changes in NextJS app router and it seems to fix all of the issues.

vercel[bot] commented 1 year ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
react-scroll-parallax ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 19, 2023 8:04pm
brendenmoore commented 1 year ago

Can confirm this fixed it for me in NextJS 14

jscottsmith commented 1 year ago

Thanks for digging into this -- was helpful to see and definitely related to strict mode, but can't replace the call to destroy with disableParallaxController since that only disables effects.

I believe the problem was mainly around how the useRef was used, it's was creating a new controller each render, and setting it to null in the cleanup as you said.

I tested this on Next 14, and it seems to fix it.

I'll publish it later this evening.

jscottsmith commented 1 year ago

Published v3.4.4

raRaRa commented 1 year ago

Closing this PR because the destroy was required. Ref: https://github.com/jscottsmith/react-scroll-parallax/pull/235