eugene
eugene

Reputation: 41685

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?

Upvotes: 14

Views: 12031

Answers (2)

Everistus Olumese
Everistus Olumese

Reputation: 391

It actually causes a re-render for me. It works, but I think it is an anti-pattern

Upvotes: -1

vkurchatkin
vkurchatkin

Reputation: 13570

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.

Upvotes: 9

Related Questions