This question is something more related to understanding internal workings of useEffect. I have read few of the articles but couldn’t find the answer to the question.
What's useEffect execution order and its internal clean-up logic in react hooks?
https://www.bussieck.com/useeffect-under-the-hood/
My question specifically is, “How react know it has to run cleanup function?” When I see useEffect, it takes a callback function and it return a function which is optional and which doesn’t get invoked instantly. So how react figures out to call it on unmount/dependency update?