0

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.

1
  • 1
    Maybe this package can help you npmjs.com/package/pubsub-js. Just emit and subscribe events inside your useEffect (don't forget unsubscribe) Commented Jun 19, 2021 at 15:17

1 Answer 1

3

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:

  • Create a common event emitter
  • useEffect to subscribe and unsubscribe to events using .on() and .off().
  • Somehow re-render the component when external state changes. I use setState() with Symbol()s.

This is a link to the full example: https://codesandbox.io/s/react-global-state-ctp6d

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution. I had little different use-case where bundles were loaded on different pages. A variation of this worked for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.