Hi,
In your code snippet, you are setting alternate key (true and false) on every click handler to the div element. key plays an important role in React reconciliation process. Setting a different key on your div element is like asking React to recreate the whole tree, which follows the process of unmounting the component and remounting it. And doing so, it runs the cleanup effect as it will do in the normal umount cycle.
Hope it helps 🙂
Thank you for detailed explanations on how useEffect deps work and how not to lie about it 😀
I have a question regarding
2. Demystifying the cause of the bug
,I just tried the code snippet and the clean up occurs.
Demo code above
What would you mean by the clean up never running?
Hi,
In your code snippet, you are setting alternate key (true and false) on every click handler to the div element. key plays an important role in React reconciliation process. Setting a different key on your
div
element is like asking React to recreate the whole tree, which follows the process of unmounting the component and remounting it. And doing so, it runs the cleanup effect as it will do in the normal umount cycle.Hope it helps 🙂
Thanks Amandeep for the explanation, links (and the nice word highlights) 😀
Thanks Sung. Happy that it was helpful. 😀