1

I am using socket.io(server) and socket.io-client(client) in react-native app and I am listening to its events in useEffect hook, all events are receiving correctly when I am on that specific component.

So how can can I receive these events on the other screens too??

Single instance for all events which will be used globally

e.g:

const app = () => {
  useEffect(() => {
    socket.on('event', (data) => {
      console.log(data)
    }
  },[])
  
 ...................
  rest of the code
 ...................
}

Now I want to listen to this event on all the screens (like DeviceEventEmitter addListner works)?

Thanks.

  • 1
    You need to create the socket instance with `createContext` In order to get the same instance in multiple components in your application. See this post: https://stackoverflow.com/questions/67642446/how-not-to-create-a-new-connection-to-scoket-io-when-updating-a-component/67642695#67642695 . After that, you can use all socket.on handlers in your app.js file importing the instance with `const socket = React.useContext(SocketContext);` – Cássio Lacerda Jun 26 '21 at 19:45
  • @CássioLacerda Thanks, I am exactly doing that now, listening to all socket events in app.js, and yap all events are receiving. – Jamal Ud Din Jun 28 '21 at 05:26
  • The same `const socket = React.useContext(SocketContext);` instance that you use in App.js, you can also use in any other component now. – Cássio Lacerda Jun 28 '21 at 13:12
  • @CássioLacerda Thank you, I have hands on Context API, now its easy to use. – Jamal Ud Din Jun 28 '21 at 13:45

0 Answers0