Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react, useEffect: Can you use global variable as a dependent variable?

window.data = {}

useEffect(() => {
// do something
}, [window.data])

Does the above code makes sense?

since window.data is global, it won't be different on renders, and the effect won't execute?

like image 747
eugene Avatar asked Mar 28 '20 13:03

eugene


1 Answers

No, that won't work. Effect could only be triggered when component is rerendered and dependencies change. Changing global variables won't cause a rerender, so the effect won't run.

like image 125
vkurchatkin Avatar answered Sep 19 '22 14:09

vkurchatkin