colorfy-software / react-native-modalfy

🥞 Modal citizen of React Native.
https://colorfy-software.gitbook.io/react-native-modalfy
MIT License
1.16k stars 48 forks source link

CloseModal causes an infinite loop when used as a dependency for useEffect #132

Closed SaryamTech closed 8 months ago

SaryamTech commented 1 year ago

Hey there!

I'm using the latest version of your library and Im facing an issue with the closeModal function causing an infinite loop when used as a dependency in an useEffect, which updates state.

I've created a snack for this. The effect has an async function to slow down the loop.

Any idea why this happens?

Thank You!

CharlesMangwa commented 8 months ago

hey @SaryamTech! sorry for not getting back to you sooner. I hope you've been able to find the root cause of this issue. if not, here's the snack with the fix: https://snack.expo.dev/IhsXIoMut-wxnJeoCm5Hq.

tldr:; useEffect is always called after each render cycle. using setSomeData() without any checks inside of it causes the component to re-render which will call useEffect and so on. simply checking for if (someData.name !== 'Harry') breaks the curse.

SaryamTech commented 8 months ago

Hey @CharlesMangwa!! Thank you for your reply! But, useEffect will only re-run when the values in the dependency array change. If the values do not change between renders, useEffect will not run. In this case, I understand that doing if (someData.name !== 'Harry') will stop the re-render, but useEffect should not run if someData is not in its dependency array. In my snack, the only thing in its dependency array is closeModal, yet it re-runs. So the question is, does closeModal's reference change on re-render.? It shouldn't if it is memorized, right? In my snack now, I've changed the dependency to openModal and it does not re-render. If I change it to closeModal, it does. Looking forward to your reply!

CharlesMangwa commented 3 weeks ago

hey @SaryamTech! thank you for your patience and the very detailed reply! apologies for getting back to you only now! 😭 indeed, you were absolutely right: all the close... methods references were not being preserved upon rerender. thank you for finding this issue and reporting it!

I've just released a fix in v3.5.5 which i tested with the repro you provided and got conclusive results. feel free to give it a try whenever and let me know!