SocketIO Hooks
What is it
socketio-hooks is a library which provides a bunch of React Hooks to easily connect and manage SocketIO.
Installation
You can get the latest release using npm:
$ npm install --save socketio-hooks
Example
In order to be able to use the hooks, you first have to render the Provider somewhere before your component and pass the connection options, like:
;; ;
IMPORTANT until we solve some issues it is recommended that you put the Provider very close to the root of your app, similar to what you would do with a Redux Provider
And then in your component, you can import any hook like this:
;; ;
API
SocketIOProvider
Prop | Required | Default | Type | Description |
---|---|---|---|---|
url | true | string | Url used to connect to the server | |
namespaces | false | [] | string[] | Namespaces to connect. If no one provided, the only namespace available will be the default ("/") |
connectionOptions | false | undefined | SocketIOClient.ConnectOpts | Object with options to be passed when connecting to SocketIO |
useNamespace()
Parameters
- namespace | String - Required. Namespace to return the socket;
useEvent()
Parameters
- event | String - Required. Event which the socket will listen to.
- namespace | String - Optional. Namespace which the event will listen.
useEmit()
Parameters
- event | String - Required. Event which the socket will emit the message to.
- namespace | String - Optional. Namespace which the socket will emit the message to.
useSocket()
Parameters
- event | String - Required. Event which the socket will listen to.
- namespace | String - Optional. Namespace which the event will listen.
- callback | Function - Required. Function that will be called once the event is triggered.