{"id":22172943,"url":"https://github.com/sumit1993/react-native-use-websocket","last_synced_at":"2025-07-26T14:31:23.117Z","repository":{"id":38851203,"uuid":"283841343","full_name":"Sumit1993/react-native-use-websocket","owner":"Sumit1993","description":"React Hook designed to provide robust WebSocket integrations to your React Native project.","archived":false,"fork":false,"pushed_at":"2023-04-12T21:05:51.000Z","size":3481,"stargazers_count":37,"open_issues_count":12,"forks_count":10,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-10-09T21:01:45.709Z","etag":null,"topics":["react","react-native","reacthooks","reconnecting-websocket","socket-io","websocket"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Sumit1993.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-07-30T17:51:50.000Z","updated_at":"2024-09-08T02:08:57.000Z","dependencies_parsed_at":"2024-06-18T20:07:08.242Z","dependency_job_id":"b7630274-1b9f-480c-80ea-d090c05cdcb7","html_url":"https://github.com/Sumit1993/react-native-use-websocket","commit_stats":{"total_commits":42,"total_committers":5,"mean_commits":8.4,"dds":"0.40476190476190477","last_synced_commit":"287378908f7f185baa3a05837258c30f94b1e3ca"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sumit1993%2Freact-native-use-websocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sumit1993%2Freact-native-use-websocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sumit1993%2Freact-native-use-websocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Sumit1993%2Freact-native-use-websocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Sumit1993","download_url":"https://codeload.github.com/Sumit1993/react-native-use-websocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227688644,"owners_count":17804595,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["react","react-native","reacthooks","reconnecting-websocket","socket-io","websocket"],"created_at":"2024-12-02T07:27:53.859Z","updated_at":"2024-12-02T07:27:54.618Z","avatar_url":"https://github.com/Sumit1993.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Native useWebSocket\n\n  \n\nReact Hook designed to provide robust WebSocket integrations to your React Native project.\n\n**Credit** (fork from): [robtaussig/react-use-websocket](https://github.com/robtaussig/react-use-websocket)\n\n  \n\n## Example Implementation\n\n  \n\n```js\nimport * as React from \"react\";\nimport useWebSocket, { ReadyState } from \"../../src\";\nimport { Button, Text, FlatList } from \"react-native\";\n\nexport default function App() {\n\n  const [socketUrl] = React.useState(\"wss://echo.websocket.org\");\n\n  const messageHistory = React.useRef \u003c any \u003e [];\n\n  const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);\n\n  messageHistory.current = React.useMemo(\n    () =\u003e messageHistory.current.concat(lastMessage),\n    [lastMessage]\n  );\n\n  const sendM = () =\u003e sendMessage(\"Hello\");\n\n  const handleClickSendMessage = React.useCallback(sendM, [sendM]);\n\n  const connectionStatus = {\n    [ReadyState.CONNECTING]: \"Connecting\",\n    [ReadyState.OPEN]: \"Open\",\n    [ReadyState.CLOSING]: \"Closing\",\n    [ReadyState.CLOSED]: \"Closed\",\n    [ReadyState.UNINSTANTIATED]: \"Uninstantiated\",\n  }[readyState];\n\n  return (\n    \u003c\u003e\n      \u003cButton\n        onPress={handleClickSendMessage}\n        disabled={readyState !== ReadyState.OPEN}\n        title={\"Click Me to send 'Hello'\"}\n      /\u003e\n      \u003cText\u003eThe WebSocket is currently {connectionStatus}\u003c/Text\u003e\n      {lastMessage ? \u003cText\u003eLast message: {lastMessage.data}\u003c/Text\u003e : null}\n      \u003cFlatList\n        keyExtractor={(item, i) =\u003e {\n          return i.toString();\n        }}\n        data={messageHistory.current}\n        renderItem={({ item }) =\u003e\n          item \u0026\u0026 item.message \u0026\u0026 \u003cText\u003e{item.message.data}\u003c/Text\u003e\n        }\n      /\u003e\n    \u003c/\u003e\n  );\n}\n\n```\n\n  \n\nFrom 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`).\n\n  \n\n## Features\n\n- Handles reconnect logic\n\n- Multiple components can (optionally) use a single WebSocket, which is closed and cleaned up when all subscribed components have unsubscribed/unmounted\n\n- Written in TypeScript\n\n- Socket.io support\n\n- No more waiting for the WebSocket to open before messages can be sent. Pre-connection messages are queued up and sent on connection\n\n- 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\n\n  \n\n## Getting Started\n\n  \n\n```sh\nnpm install react-native-use-websocket\n```\n\n  \n\n```js\nimport useWebSocket from 'react-native-use-websocket';\n\n// In functional React component\n// This can also be an async getter function. See notes below on Async Urls.\n\nconst socketUrl = 'wss://echo.websocket.org';\nconst {\n    sendMessage,\n    sendJsonMessage,\n    lastMessage,\n    lastJsonMessage,\n    readyState,\n    getWebSocket\n} = useWebSocket(socketUrl, {\n    onOpen: () =\u003e console.log('opened'),\n    //Will attempt to reconnect on all close events, such as server shutting down\n    shouldReconnect: (closeEvent) =\u003e true,\n});\n```\n\n  \n\n## Requirements\n\n- React 16.8+\n\n- Cannot be used within a class component (must be a functional component that supports React Hooks)\n\n  \n\n## Async Urls\n\nInstead 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.\n\n  \n\n```js\nimport useWebSocket from 'react-use-websocket';\n\n// In functional React component\n\nconst getSocketUrl = useCallback(() =\u003e {\n    return new Promise(resolve =\u003e {\n        setTimeout(() =\u003e {\n            resolve('wss://echo.websocket.org');\n        }, 2000);\n    });\n}, []);\n\nconst {\n    sendMessage,\n    lastMessage,\n    readyState,\n    getWebSocket\n} = useWebSocket(getSocketUrl, STATIC_OPTIONS);\n```\n\n  \n\n## API\n\n  \n\n### sendMessage\n\n```ts\ntype  sendMessage = (message: string) =\u003e  void;\n```\n\nThe 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.\n\n  \n\n### sendJsonMessage\n\n```ts\ntype  sendJsonMessage = (message: any) =\u003e  void;\n```\n\nMessage will first be passed through `JSON.stringify`.\n\n  \n\n### lastMessage\n\n```ts\ntype  lastMessage = WebSocketEventMap['message'];\n```\n\nWill be an unparsed `MessageEvent` received from the WebSocket.\n\n  \n\n### lastJsonMessage\n\n```ts\ntype  lastMessage = any;\n```\n\nA `JSON.parse`d object from the `lastMessage`. If `lastMessage` is not a valid JSON string, `lastJsonMessage` will be an empty object.\n\n  \n\n### readyState\n\n```ts\nenum ReadyState {\n\tUNINSTANTIATED = -1,\n\tCONNECTING = 0,\n\tOPEN = 1,\n\tCLOSING = 2,\n\tCLOSED = 3\n}\n```\n\nWill 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`)\n\n  \n\n### getWebSocket\n\n```ts\ntype  getWebSocket = () =\u003e  WebSocket | Proxy\u003cWebSocket\u003e\n```\n\nIf 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:\n\n  \n\n```js\nconst {\n    sendMessage,\n    lastMessage,\n    readyState,\n    getWebSocket\n} = useWebSocket('wss://echo.websocket.org', {\n    share: true\n});\n\nuseEffect(() =\u003e {\n  \n    console.log(getWebSocket().binaryType) //=\u003e 'blob'\n\n    //Change binaryType property of WebSocket\n    getWebSocket().binaryType = 'arraybuffer';\n    console.log(getWebSocket().binaryType) //=\u003e 'arraybuffer'\n\n    //Attempt to change event handler\n    getWebSocket().onmessage = console.log //=\u003e A warning is logged to console: 'The WebSocket's event handlers should be defined through the options object passed into useWebSocket.'\n\n    //Attempt to change an immutable property\n    getWebSocket().url = 'www.google.com';\n    console.log(getWebSocket().url); //=\u003e 'wss://echo.websocket.org'\n\n    //Attempt to call webSocket#send\n    getWebSocket().send('Hello from WebSocket'); //=\u003e 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.'\n\n}, []);\n```\n\nIf 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.\n\n  \n\n## Reconnecting\n\nBy 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:\n\n  \n\n```js\nconst didUnmount = useRef(false);\n\nconst [sendMessage, lastMessage, readyState] = useWebSocket(\n    'wss://echo.websocket.org', {\n        shouldReconnect: (closeEvent) =\u003e {\n          \n            /*\n            useWebSocket will handle unmounting for you, but this is an example of a\n            case in which you would not want it to automatically reconnect\n            */\n            return didUnmount.current === false;\n        },\n        reconnectAttempts: 10,\n        reconnectInterval: 3000,\n    });\n\nuseEffect(() =\u003e {\n    return () =\u003e {\n        didUnmount.current = true;\n    };\n}, []);\n```\n\n  \n\n## Options\n\n```ts\ninterface Options {\n    share ? : boolean;\n    shouldReconnect ? : (event: WebSocketEventMap['close']) =\u003e boolean;\n    reconnectInterval ? : number;\n    reconnectAttempts ? : number;\n    filter ? : (message: WebSocketEventMap['message']) =\u003e boolean;\n    retryOnError ? : boolean;\n    onOpen ? : (event: WebSocketEventMap['open']) =\u003e void;\n    onClose ? : (event: WebSocketEventMap['close']) =\u003e void;\n    onMessage ? : (event: WebSocketEventMap['message']) =\u003e void;\n    onError ? : (event: WebSocketEventMap['error']) =\u003e void;\n    onReconnectStop?: (numAttempts: number) =\u003e void;\n    fromSocketIO ? : boolean;\n    queryParams ? : {\n        [key: string]: string | number;\n    };\n    protocols ? : string | string[];\n    options ? : {\n        [optionName: string]: any;\n        headers: {\n            [headerName: string]: string;\n        };\n    } | null;\n}\n```\n\n### shouldReconnect\n\nSee section on [Reconnecting](#Reconnecting).\n\n  \n\n### reconnectInterval\n\nNumber of milliseconds to wait until it attempts to reconnect. Default is 5000.\n\n  \n\n### Event Handlers: Callback\n\nEach 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.\n\n### onReconnectStop\nIf provided in options, will be called when websocket exceeds reconnect limit, either as provided in the options or the default value of 20.  \n\n### share: Boolean\n\nIf 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.\n\n  \n\n### fromSocketIO: Boolean\n\nSocketIO 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`.\n\n  \n\n### queryParams: Object\n\nPass an object representing an arbitrary number of query parameters, which will be converted into stringified query params and appended to the WebSocket url.\n\n  \n\n```js\nconst queryParams = {\n    'user_id': 1,\n    'room_id': 5\n};\n\n//\u003curl\u003e?user_id=1\u0026room_id=5\n```\n\n  \n\n### useSocketIO\n\nSocketIO sends messages in a format that isn't JSON-parsable. One example is:\n\n```\n\"42[\"Action\",{\"key\":\"value\"}]\"\n```\n\nAn extension of this hook is available by importing `useSocketIO`:\n\n```js\nimport { useSocketIO } from 'react-use-websocket';\n\n//Same API in component\nconst {\n    sendMessage,\n    lastMessage,\n    readyState\n} = useSocketIO('socket.io');\n```\n\nIt is important to note that `lastMessage` will not be a `MessageEvent`, but instead an object with two keys: `type` and `payload`.\n\n  \n\n### Filter: Callback\n\nIf 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.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsumit1993%2Freact-native-use-websocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsumit1993%2Freact-native-use-websocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsumit1993%2Freact-native-use-websocket/lists"}