Reputation: 1808
I have two react applications, i.e. appA
and appB
(Both have thier own ReactDOM.render()
method) and they generate different build files i.e. bundleA.js
and bundleB.js
respectively. These bundles are loaded in a third application i.e. container
(a plain js app).
There are some common states shared between them using global/window variables. For instance,
window.pets = [
{name: 'dog'},
{name: 'cat'}
]
Let's say appA
add/remove a pet to/from window.pets
. It's updated in appA
but not in appB
. I tried using useEffect
in both applications, as follow:
//object dependecy dependency
useEffect(()=>{
console.log(window.pets);
},[window.pets])
//Also tried stringyting object
useEffect(()=>{
console.log(window.pets);
},[JSON.stringify(window.pets)])
But it's not capturing the global state change in other application. Any suggestion will be helpful.
Upvotes: 0
Views: 115
Reputation: 2098
The useEffect
hook only gets called every time the component re-renders. You need to make sure that your component gets re-rendered when window.pets
changes. Like @Raman Nikitsenka commented, you can use some sort of event emitter to re-render your component when window.pets
changes.
These are the key things you have to do:
useEffect
to subscribe and unsubscribe to events using .on()
and .off()
.setState()
with Symbol()
s.This is a link to the full example: https://codesandbox.io/s/react-global-state-ctp6d
Upvotes: 3