Gathering detailed insights and metrics for react-native-use-websocket
Gathering detailed insights and metrics for react-native-use-websocket
Gathering detailed insights and metrics for react-native-use-websocket
Gathering detailed insights and metrics for 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.
npm install react-native-use-websocket
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
38 Stars
70 Commits
10 Forks
1 Watching
7 Branches
4 Contributors
Updated on 13 Nov 2024
TypeScript (60.13%)
Java (17.12%)
Ruby (9.68%)
Objective-C (8.73%)
JavaScript (3.89%)
C (0.28%)
Swift (0.18%)
Cumulative downloads
Total Downloads
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
2
19
React Hook designed to provide robust WebSocket integrations to your React Native project.
Credit (fork from): robtaussig/react-use-websocket
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
).
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
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});
React 16.8+
Cannot be used within a class component (must be a functional component that supports React Hooks)
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);
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.
1type sendJsonMessage = (message: any) => void;
Message will first be passed through JSON.stringify
.
1type lastMessage = WebSocketEventMap['message'];
Will be an unparsed MessageEvent
received from the WebSocket.
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.
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
)
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.
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}, []);
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}
See section on Reconnecting.
Number of milliseconds to wait until it attempts to reconnect. Default is 5000.
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.
If provided in options, will be called when websocket exceeds reconnect limit, either as provided in the options or the default value of 20.
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.
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
.
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
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
.
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
Reason
binaries present in source code
Details
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
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
44 existing vulnerabilities detected
Details
Score
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 More