Best Way To Globally Instantiate Ably Connection in React Native

668 views Asked by At

I am building a React Native game with multiple screens. I am trying to instantiate Ably one time and use it throughout the application without having to call new Ably('api-key') on every screen, as this is creating multiple new connections and making it impossible to keep a single connectionId. Is there a way to architect this so that I can define

const client = new Ably('api-key')

one time in App.js and use it throughout the other screens? Either by passing it as props through React Navigation props or using Context? The documentation on this is sparse as most of their documentation only uses this on one page.

1

There are 1 answers

0
Richie Jarvis On BEST ANSWER

Redux will not work. You can create an Ably client and pass it to other components using props, or just use React context to make it available to the whole application. Using redux to store an Ably client will cause an error since Ably clients aren’t serialisable.

See https://reactjs.org/docs/context.html for more info.

Here are some examples:

https://github.com/ably-labs/react-hooks https://ably.com/blog/ably-react-hooks-npm-package

Cheers,

Richie