Quick tip: sharing data between mobile plugin elements using globalThis

Just a quick tip for anyone looking to share data between multiple elements in a mobile plugin.

With web elements this was never much of a problem, because you can use the global window object as a bridge between elements. Mobile elements are a different story, there’s no window (or DOM) in the React Native runtime. The good news is there’s an equivalent: the globalThis object, which is available in both environments and works the same way as a shared space.

Here’s a quick example of each:

Web element

window.sharedVar = "example shared text";
window.sharedFunc = function () { /* ... */ };

Mobile element

globalThis.sharedVar = "example shared text";
globalThis.sharedFunc = function () { /* ... */ };

One element writes a value (or a function) onto globalThis, and another element can read it. A handy pattern is to have one element register a function on globalThis that a second element can call, for example to notify it that some shared data has changed.

Hope it’s useful!

Paul

Awesome tip. I’ve been looking at dabbling in some mobile plugins soon and use the window a lot in web plugins.

Ah glad it helped!