colorfy-software / react-native-modalfy

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

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

Closed SaryamTech closed 4 months ago

SaryamTech commented 7 months 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 4 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 3 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!