1

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?

Alok Raj
  • 328
  • 3
  • 9

1 Answers1

0

So you've already read that ordering really matters and React stores "internal data" per hook's position. Similarly how useState stores "current value", useEffect also can save some internal data: last values for dependencies list(initially it's []) and value returned when last time this specific useEffect has run(initially undefined).

Then once internal comparison for dependencies says "ok, dependencies are different, need to run this useEffect again" React takes result from last call and whether it's a function - runs it without any arguments(cleanup).

Next step effect itself is executed - and whathever it returns - is stored back into slot for current hook, to be checked/run next time.

Sure, also cleanup will be run on unmount. If it is a function.

skyboyer
  • 22,209
  • 7
  • 57
  • 64