13
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?

eugene
  • 39,839
  • 68
  • 255
  • 489
  • just test it? should work ... but "Global variables are considered an anti-pattern in almost any programming language" – xadm Mar 28 '20 at 13:31
  • wel, I find it not working (although I'm setting a Webview's window.test from RN) and wasn't sure .. ya I could have tested it :( – eugene Mar 28 '20 at 13:35

2 Answers2

9

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.

vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
  • I'm using `useLayoutEffect` for it, and I stored the `window.myGodDamnedVariable` into another variable, This causes the ESLint to shutup about violating hook dependencies. I'm still looking for a better way tho, I am forced to do this for now – DarkSuniuM Apr 06 '21 at 08:29
  • 1
    That doesn't really help. That exact piece of code doesn't work, but what does? What's a pattern that would let us use a global variable (and an "update" hook)? – fregante Oct 28 '22 at 10:00
0

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

Everistus Olumese
  • 384
  • 1
  • 4
  • 16