{"id":15290510,"url":"https://github.com/kamiloox/use-socket-io-react","last_synced_at":"2025-04-13T10:12:23.759Z","repository":{"id":59190854,"uuid":"532076944","full_name":"kamiloox/use-socket-io-react","owner":"kamiloox","description":"React.js wrapper for socket.io-client","archived":false,"fork":false,"pushed_at":"2023-10-12T13:08:55.000Z","size":146,"stargazers_count":6,"open_issues_count":3,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-09T09:39:46.392Z","etag":null,"topics":["reactjs","socket-io","typescript","websocket"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/use-socket-io-react","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/kamiloox.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"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":"2022-09-02T20:57:51.000Z","updated_at":"2025-03-24T17:35:50.000Z","dependencies_parsed_at":"2024-11-15T03:33:16.635Z","dependency_job_id":"320d7f10-66e6-4fb6-879d-c9154ed7c8bf","html_url":"https://github.com/kamiloox/use-socket-io-react","commit_stats":{"total_commits":20,"total_committers":2,"mean_commits":10.0,"dds":0.35,"last_synced_commit":"6631304340107e9c6e2451050cea7f2e28fb5827"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kamiloox%2Fuse-socket-io-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kamiloox%2Fuse-socket-io-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kamiloox%2Fuse-socket-io-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kamiloox%2Fuse-socket-io-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kamiloox","download_url":"https://codeload.github.com/kamiloox/use-socket-io-react/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248695482,"owners_count":21146956,"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":["reactjs","socket-io","typescript","websocket"],"created_at":"2024-09-30T16:08:26.829Z","updated_at":"2025-04-13T10:12:23.735Z","avatar_url":"https://github.com/kamiloox.png","language":"TypeScript","readme":"\u003cdiv align=\"center\"\u003e\n  \u003cp\u003e\n  Written with ❤️ It's 100% typesafe to make React.js developer experience better with socket.io-client.\n  \u003c/p\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Socket.io-black?style=for-the-badge\u0026logo=socket.io\u0026badgeColor=010101\" alt=\"Socket.io\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/TypeScript-007ACC?style=for-the-badge\u0026logo=typescript\u0026logoColor=white\" alt=\"TypeScript\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/react-%2320232a.svg?style=for-the-badge\u0026logo=react\u0026logoColor=%2361DAFB\" alt=\"React.js\"\u003e\n\n\u003c/div\u003e\n\n## Key features\n\n- Module augmentation to reuse your types that are on a backend. More on that [here](#module-augmentation)\n- TypeScript support\n- Reusable React.js hooks\n\n## Installation\n\n- With yarn\n\n  ```sh\n  yarn add use-socket-io-react\n  ```\n\n- With npm\n\n  ```sh\n  npm install use-socket-io-react\n  ```\n\n## Setup\n\nWrap the application with a `SocketProvider`. For example, with React 18 it can be done like so:\n\n```ts\nconst SERVER_URI = 'http://localhost:4000';\n\nReactDOM.render(\n  \u003cSocketProvider uri={SERVER_UR}\u003e\n    \u003cApp /\u003e\n  \u003c/SocketProvider\u003e,\n  document.getElementById('root'),\n);\n```\n\nThe URI prop needs to point to a backend server. Don't forget about handling a [CORS policy](https://socket.io/docs/v4/handling-cors/#configuration) on a server because since version 3 of a `socket.io` it needs to be set explicitly.\n\n## Handling events\n\nThere is a hook called `useSocketEvent`. As a first argument, it takes an event name and in a resolution, it returns an object with a `data` array. Values in an array match to an order in which values are passed to an `io.emit` on a server.\n\n```ts\n// Server\nio.emit('alert', 'Hey, you are the best!');\n```\n\n```ts\n// Client\nconst {\n  data: [alert],\n} = useSocketEvent\u003c[string]\u003e('alert');\n\nif (alert) {\n  return \u003cp\u003eYou received an alert: ${alert}\u003c/p\u003e;\n}\n```\n\nAlternatively `useSocketEvent` provides a handler callback that gets dispatched when the socket receives an event.\n\n```ts\n// Server\nio.emit('chat', 'Hello John!', '12:38');\n```\n\n```ts\n// Client\nconst [messages, setMessages] = useState\u003c\n  Array\u003c{ message: string; sentAt: string }\u003e\n\u003e([]);\n\nconst handleMessage = ([message, sentAt]: [string, string]) =\u003e {\n  setMessages([...messages, { message: message, sentAt: sentAt }]);\n};\n\nuseSocketEvent\u003c[string, string]\u003e('chat', {\n  handler: handleMessage,\n});\n\nreturn (\n  \u003csection\u003e\n    {messages.map(({ message, sentAt }) =\u003e (\n      \u003cp\u003e\n        {message} ({sentAt})\n      \u003c/p\u003e\n    ))}\n  \u003c/section\u003e\n);\n```\n\n## Emitting events\n\nFor emitting there is a hook called `useSocketEmit`. It doesn't take any argument but it returns an `emit` function.\n\n```ts\nconst { emit } = useSocketEmit();\n\nemit\u003c[string]\u003e('message', ['Hey, this is my message']);\n```\n\nYou can provide a generic of how your emitted values need to look, but that's not recommended. Take a look at [module augmentation](#module-augmentation)\n\n## Socket state\n\nHook called `useSocket` stores values about a current socket state. It knows e.g. if a socket is either connected or there is some error.\n\n```ts\nconst {\n  socket,\n  status,\n  isConnected,\n  isConnecting,\n  isDisconnected,\n  disconnectReason,\n  isError,\n  error,\n} = useSocket();\n\n// Or you can check: status === 'error'\nif (isError) {\n  return \u003cp\u003eError! {error}\u003c/p\u003e;\n}\n\nif (isDisconnected) {\n  return \u003cp\u003eSocket disconnected {disconnectReason}\u003c/p\u003e;\n}\n\nif (isConnecting) {\n  return \u003cp\u003eIs loading\u003c/p\u003e;\n}\n```\n\nIn addition, `useSocket` returns a native socket from a `socket.io-client` if some feature is needed that's currently beyond this library.\n\n\u003ch2 id=\"module-augmentation\"\u003eModule augmentation\u003c/h2\u003e\n\nSocket.io introduces [TypeScript support](https://socket.io/docs/v4/typescript/). This library supports this idea too. It's possible to abandon passing generic to every `useSocketEvent` and `useSocketEmit` hook thankfully to a module [augmentation feature](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).\n\nIn the a root of a project (e.g. in the `src`) create a file called `types/use-socket-io-react.d.ts` and paste this.\n\n```ts\nimport 'use-socket-io-react';\n\ndeclare module 'use-socket-io-react' {\n  interface ServerToClientEvents {\n    chat: (message: string, sentAt: number) =\u003e void;\n  }\n\n  interface ClientToServerEvents {\n    alert: (content: string) =\u003e void;\n  }\n}\n```\n\nThese interfaces are copied directly from a backend. There is no need to worry about the specific conventions for this package. If on a backend server a TypeScript is used then it's easy to extend it.\n\n```ts\nconst { emit } = useSocketEmit();\n\n// Argument of type '[]' is not assignable to parameter of type '[content: string]'.\n// Source has 0 element(s) but target requires 1.\nemit('alert', []);\n```\n\n```ts\nconst handleMessage: EventHandler\u003c'chat'\u003e = ([message]) =\u003e {\n  console.log(`There is a message ${message}`);\n};\n\nuseSocketEvent('chat', {\n  handler: handleMessage,\n});\n```\n\n\u003e Disclaimer. If this feature doesn't work try adding a path to a `typeRoots` in a `tsconfig.json`.\n\n```ts\n{\n  \"compilerOptions\": {\n    \"typeRoots\": [\"./src/types\"]\n  },\n}\n```\n\n### Additional notes\n\n- Package uses the 4th major version of a `socket.io-client`.\n- This project uses [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) convention\n- This is still in development. But there are more incoming updates in the future!\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkamiloox%2Fuse-socket-io-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkamiloox%2Fuse-socket-io-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkamiloox%2Fuse-socket-io-react/lists"}