React Socket.io Hooks
SocketProvider
SocketProvider connects to a websocket server and begins listening to emitted events. All emitted events will hit a reducer and update state.
Props
uri: string
- The location of the websocket serverreducer: (state, action) => {}
- A reducer function to handle incoming eventsaction: { type: string, payload: any }
initialState
- The initial state of the application (defaults to{}
)
const reducer = { console return state;}; { return <SocketProvider uri="http://localhost:7891" reducer=reducer initialState={}> <h1>Hello World</h1> </SocketProvider> ;}
useSocket
This hook returns the connected socket
const Counter = { const socket = ;}
useSocketState
This hook returns the current state;
const Counter = { const state = ;}
useSocketSelector
This hook takes a selector to return selected information from state (like redux).
const Counter = { const count = ;}
useEmit
This hook returns the emit function to emit a socket event.
const Counter = { const emit = ;}
useEmitEvent
This hook returns the a function to emit and event to the websocket server
const Counter = { const emitEvent = ;}
useSocketDispatch
This hook returns a dispatch function which lets you dispatch an action to your reducer.
Example
;; const reducer = { } const Counter = { const increment = ; const decrement = ; return <> <button onClick= >Decrement</button> <button onClick= >Increment</button> </> } const Display = { const state = ; console return <p>statecount</p> ;} { return <SocketProvider uri="http://localhost:7891" reducer=reducer initialState= count: 0 > <Counter /> <Display /> </SocketProvider> ;}
const http = ;const io = http; let count = 0; io; http