Why does cleanUp runs on only unmount if dependencies array is empty in React?

Viewed 9

The react documentation says, If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

But it is in controdiction with the behaviour if some values are passed to dependency array in useEffect.

e.g:

useEffect(()=> {
  console.log('effect ran')
  return cleanupAction(){console.log('cleanup action')}
}, [props.value])

Here for every render when the effect will run, a cleanup will run before next render. so, cleanup will only run if the effect was run.

but in other scenario.

useEffect(()=> {
  console.log('effect ran')
  return cleanupAction(){console.log('cleanup action')}
}, [])

Here in this case, the effect will run only on first render. and I expect the cleanup to run only before the second render. Then, why does the cleanup runs on unmount.

Because, I assume, when a render caused a effect to run. a cleanup will run before next render. So, it is not happening in this case.

0 Answers
Related