Installations
npm install react-native-use-websocket
Developer
Sumit1993
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
16.0.0
NPM Version
7.20.0
Statistics
38 Stars
70 Commits
10 Forks
1 Watching
7 Branches
4 Contributors
Updated on 13 Nov 2024
Languages
TypeScript (60.13%)
Java (17.12%)
Ruby (9.68%)
Objective-C (8.73%)
JavaScript (3.89%)
C (0.28%)
Swift (0.18%)
Total Downloads
Cumulative downloads
Total Downloads
111,089
Last day
-25.1%
586
Compared to previous day
Last week
0.2%
2,956
Compared to previous week
Last month
30.7%
13,012
Compared to previous month
Last year
153%
73,810
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Peer Dependencies
2
Dev Dependencies
19
React Native useWebSocket
React Hook designed to provide robust WebSocket integrations to your React Native project.
Credit (fork from): robtaussig/react-use-websocket
Example Implementation
1import * as React from "react"; 2import useWebSocket, { ReadyState } from "../../src"; 3import { Button, Text, FlatList } from "react-native"; 4 5export default function App() { 6 7 const [socketUrl] = React.useState("wss://echo.websocket.org"); 8 9 const messageHistory = React.useRef < any > []; 10 11 const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl); 12 13 messageHistory.current = React.useMemo( 14 () => messageHistory.current.concat(lastMessage), 15 [lastMessage] 16 ); 17 18 const sendM = () => sendMessage("Hello"); 19 20 const handleClickSendMessage = React.useCallback(sendM, [sendM]); 21 22 const connectionStatus = { 23 [ReadyState.CONNECTING]: "Connecting", 24 [ReadyState.OPEN]: "Open", 25 [ReadyState.CLOSING]: "Closing", 26 [ReadyState.CLOSED]: "Closed", 27 [ReadyState.UNINSTANTIATED]: "Uninstantiated", 28 }[readyState]; 29 30 return ( 31 <> 32 <Button 33 onPress={handleClickSendMessage} 34 disabled={readyState !== ReadyState.OPEN} 35 title={"Click Me to send 'Hello'"} 36 /> 37 <Text>The WebSocket is currently {connectionStatus}</Text> 38 {lastMessage ? <Text>Last message: {lastMessage.data}</Text> : null} 39 <FlatList 40 keyExtractor={(item, i) => { 41 return i.toString(); 42 }} 43 data={messageHistory.current} 44 renderItem={({ item }) => 45 item && item.message && <Text>{item.message.data}</Text> 46 } 47 /> 48 </> 49 ); 50} 51
From the example above, the component will rerender every time the readyState
of the WebSocket changes, as well as when the WebSocket receives a message (which will change lastMessage
). sendMessage
is a memoized callback that will pass the message to the current WebSocket (referenced to internally with useRef
).
Features
-
Handles reconnect logic
-
Multiple components can (optionally) use a single WebSocket, which is closed and cleaned up when all subscribed components have unsubscribed/unmounted
-
Written in TypeScript
-
Socket.io support
-
No more waiting for the WebSocket to open before messages can be sent. Pre-connection messages are queued up and sent on connection
-
Provides direct access to unshared WebSockets, while proxying shared WebSockets. Proxied WebSockets provide subscribers controlled access to the underlying (shared) WebSocket, without allowing unsafe behavior
Getting Started
1npm install react-native-use-websocket
1import useWebSocket from 'react-native-use-websocket'; 2 3// In functional React component 4// This can also be an async getter function. See notes below on Async Urls. 5 6const socketUrl = 'wss://echo.websocket.org'; 7const { 8 sendMessage, 9 sendJsonMessage, 10 lastMessage, 11 lastJsonMessage, 12 readyState, 13 getWebSocket 14} = useWebSocket(socketUrl, { 15 onOpen: () => console.log('opened'), 16 //Will attempt to reconnect on all close events, such as server shutting down 17 shouldReconnect: (closeEvent) => true, 18});
Requirements
-
React 16.8+
-
Cannot be used within a class component (must be a functional component that supports React Hooks)
Async Urls
Instead of passing a string as the first argument to useWebSocket, you can pass a function that returns a string (or a promise that resolves to a string). It's important to note, however, that other rules still apply -- namely, that if the function reference changes, then it will be called again, potentially instantiating a new WebSocket if the returned url changes.
1import useWebSocket from 'react-use-websocket'; 2 3// In functional React component 4 5const getSocketUrl = useCallback(() => { 6 return new Promise(resolve => { 7 setTimeout(() => { 8 resolve('wss://echo.websocket.org'); 9 }, 2000); 10 }); 11}, []); 12 13const { 14 sendMessage, 15 lastMessage, 16 readyState, 17 getWebSocket 18} = useWebSocket(getSocketUrl, STATIC_OPTIONS);
API
sendMessage
1type sendMessage = (message: string) => void;
The argument sent through sendMessage will be passed directly to WebSocket#send
. sendMessage
will be static, and thus can be passed down through children components without triggering prop changes. Messages sent before the WebSocket is open will be queued up and sent on connection.
sendJsonMessage
1type sendJsonMessage = (message: any) => void;
Message will first be passed through JSON.stringify
.
lastMessage
1type lastMessage = WebSocketEventMap['message'];
Will be an unparsed MessageEvent
received from the WebSocket.
lastJsonMessage
1type lastMessage = any;
A JSON.parse
d object from the lastMessage
. If lastMessage
is not a valid JSON string, lastJsonMessage
will be an empty object.
readyState
1enum ReadyState { 2 UNINSTANTIATED = -1, 3 CONNECTING = 0, 4 OPEN = 1, 5 CLOSING = 2, 6 CLOSED = 3 7}
Will be an integer representing the readyState
of the WebSocket. -1
is not a valid WebSocket readyState
, but instead indicates that the WebSocket has not been instantiated yet (either because the url is null
or connect param is false
)
getWebSocket
1type getWebSocket = () => WebSocket | Proxy<WebSocket>
If the WebSocket is shared, calling this function will lazily instantiate a Proxy
instance that wraps the underlying WebSocket. You can get and set properties on the return value that will directly interact with the WebSocket, however certain properties/methods are protected (cannot invoke close
or send
, and cannot redefine any of the event handlers like onmessage
, onclose
, onopen
and onerror
. An example of using this:
1const { 2 sendMessage, 3 lastMessage, 4 readyState, 5 getWebSocket 6} = useWebSocket('wss://echo.websocket.org', { 7 share: true 8}); 9 10useEffect(() => { 11 12 console.log(getWebSocket().binaryType) //=> 'blob' 13 14 //Change binaryType property of WebSocket 15 getWebSocket().binaryType = 'arraybuffer'; 16 console.log(getWebSocket().binaryType) //=> 'arraybuffer' 17 18 //Attempt to change event handler 19 getWebSocket().onmessage = console.log //=> A warning is logged to console: 'The WebSocket's event handlers should be defined through the options object passed into useWebSocket.' 20 21 //Attempt to change an immutable property 22 getWebSocket().url = 'www.google.com'; 23 console.log(getWebSocket().url); //=> 'wss://echo.websocket.org' 24 25 //Attempt to call webSocket#send 26 getWebSocket().send('Hello from WebSocket'); //=> No message is sent, and no error thrown (a no-op function was returned), but an error will be logged to console: 'Calling methods directly on the WebSocket is not supported at this moment. You must use the methods returned by useWebSocket.' 27 28}, []);
If the WebSocket is not shared (via options), then the return value is the underlying WebSocket, and thus methods such as close
and send
can be accessed and used.
Reconnecting
By default, useWebSocket
will not attempt to reconnect to a WebSocket. This behavior can be modified through a few options. To attempt to reconnect on error events, set Options#retryOnError
to true
. Because CloseEvent
s are less straight forward (e.g., was it triggered intentionally by the client or by something unexpected by the server restarting?), Options#shouldReconnect
must be provided as a callback, with the socket CloseEvent
as the first and only argument, and a return value of either true
or false
. If true
, useWebSocket
will attempt to reconnect up to a specified number of attempts (with a default of 20
) at a specified interval (with a default of 5000
(ms)). The option properties for attempts is Options#reconnectAttempts
and the interval is Options#reconnectInterval
. As an example:
1const didUnmount = useRef(false);
2
3const [sendMessage, lastMessage, readyState] = useWebSocket(
4 'wss://echo.websocket.org', {
5 shouldReconnect: (closeEvent) => {
6
7 /*
8 useWebSocket will handle unmounting for you, but this is an example of a
9 case in which you would not want it to automatically reconnect
10 */
11 return didUnmount.current === false;
12 },
13 reconnectAttempts: 10,
14 reconnectInterval: 3000,
15 });
16
17useEffect(() => {
18 return () => {
19 didUnmount.current = true;
20 };
21}, []);
Options
1interface Options { 2 share ? : boolean; 3 shouldReconnect ? : (event: WebSocketEventMap['close']) => boolean; 4 reconnectInterval ? : number; 5 reconnectAttempts ? : number; 6 filter ? : (message: WebSocketEventMap['message']) => boolean; 7 retryOnError ? : boolean; 8 onOpen ? : (event: WebSocketEventMap['open']) => void; 9 onClose ? : (event: WebSocketEventMap['close']) => void; 10 onMessage ? : (event: WebSocketEventMap['message']) => void; 11 onError ? : (event: WebSocketEventMap['error']) => void; 12 onReconnectStop?: (numAttempts: number) => void; 13 fromSocketIO ? : boolean; 14 queryParams ? : { 15 [key: string]: string | number; 16 }; 17 protocols ? : string | string[]; 18 options ? : { 19 [optionName: string]: any; 20 headers: { 21 [headerName: string]: string; 22 }; 23 } | null; 24}
shouldReconnect
See section on Reconnecting.
reconnectInterval
Number of milliseconds to wait until it attempts to reconnect. Default is 5000.
Event Handlers: Callback
Each of Options#onMessage
, Options#onError
, Options#onClose
, and Options#onOpen
will be called on the corresponding WebSocket event, if provided. Each will be passed the same event provided from the WebSocket.
onReconnectStop
If provided in options, will be called when websocket exceeds reconnect limit, either as provided in the options or the default value of 20.
share: Boolean
If set to true
, a new WebSocket will not be instantiated if one for the same url has already been created for another component. Once all subscribing components have either unmounted or changed their target socket url, shared WebSockets will be closed and cleaned up. No other APIs should be affected by this.
fromSocketIO: Boolean
SocketIO acts as a layer on top of the WebSocket protocol, and the required client-side implementation involves a few peculiarities. If you have a SocketIO back-end, or are converting a client-side application that uses the socketIO library, setting this to true
might be enough to allow useWebSocket
to work interchangeably. This is an experimental option as the SocketIO library might change its API at any time. This was tested with Socket IO 2.1.1
.
queryParams: Object
Pass an object representing an arbitrary number of query parameters, which will be converted into stringified query params and appended to the WebSocket url.
1const queryParams = { 2 'user_id': 1, 3 'room_id': 5 4}; 5 6//<url>?user_id=1&room_id=5
useSocketIO
SocketIO sends messages in a format that isn't JSON-parsable. One example is:
"42["Action",{"key":"value"}]"
An extension of this hook is available by importing useSocketIO
:
1import { useSocketIO } from 'react-use-websocket'; 2 3//Same API in component 4const { 5 sendMessage, 6 lastMessage, 7 readyState 8} = useSocketIO('socket.io');
It is important to note that lastMessage
will not be a MessageEvent
, but instead an object with two keys: type
and payload
.
Filter: Callback
If a function is provided with the key filter
, incoming messages will be passed through the function, and only if it returns true
will the hook pass along the lastMessage
and update your component.
No vulnerabilities found.
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
binaries present in source code
Details
- Warn: binary detected: example/android/gradle/wrapper/gradle-wrapper.jar:1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Reason
44 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-f5x2-xv93-4p23
- Warn: Project is vulnerable to: GHSA-gmpm-xp43-f7g6
- Warn: Project is vulnerable to: GHSA-pf27-929j-9pmm
- Warn: Project is vulnerable to: GHSA-327c-qx3v-h673
- Warn: Project is vulnerable to: GHSA-x4cf-6jr3-3qvp
- Warn: Project is vulnerable to: GHSA-mph8-6787-r8hw
- Warn: Project is vulnerable to: GHSA-7mhc-prgv-r3q4
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-r683-j2x4-v87g
- Warn: Project is vulnerable to: GHSA-rxrc-rgv4-jpvx
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-g4rg-993r-mgx7
- Warn: Project is vulnerable to: GHSA-fhg7-m89q-25r3
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
- Warn: Project is vulnerable to: GHSA-fwr7-v2mv-hh25
- Warn: Project is vulnerable to: GHSA-ff7x-qrg7-qggm
- Warn: Project is vulnerable to: GHSA-ghr5-ch3p-vcr6
- Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
- Warn: Project is vulnerable to: GHSA-rc47-6667-2j5j
- Warn: Project is vulnerable to: GHSA-p6mc-m468-83gw
- Warn: Project is vulnerable to: GHSA-29mw-wpgm-hmr9
- Warn: Project is vulnerable to: GHSA-35jh-r3h4-6jhm
- Warn: Project is vulnerable to: GHSA-jgrx-mgxx-jf9v
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-7p7h-4mm5-852v
- Warn: Project is vulnerable to: GHSA-38fc-wpqx-33j7
- Warn: Project is vulnerable to: GHSA-7jxr-cg7f-gpgv
- Warn: Project is vulnerable to: GHSA-xj72-wvfv-8985
- Warn: Project is vulnerable to: GHSA-ch3r-j5x3-6q2m
- Warn: Project is vulnerable to: GHSA-p5gc-c584-jj6v
- Warn: Project is vulnerable to: GHSA-whpj-8f3w-67p5
- Warn: Project is vulnerable to: GHSA-cchq-frgv-rjh5
- Warn: Project is vulnerable to: GHSA-g644-9gfx-q4q4
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp
Score
1.9
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to react-native-use-websocket
ws
Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js
@expo/dev-server
Development servers for starting React Native projects
@react-native/dev-middleware
Dev server middleware for React Native
sockjs-client
SockJS-client is a browser JavaScript library that provides a WebSocket-like object.