{"id":40447847,"url":"https://github.com/rohitsoni007/react-socket","last_synced_at":"2026-01-20T17:06:04.473Z","repository":{"id":143785766,"uuid":"452381457","full_name":"rohitsoni007/react-socket","owner":"rohitsoni007","description":"React Socket Client - React.js Wrapper for Socket.IO Client","archived":false,"fork":false,"pushed_at":"2025-12-16T14:24:27.000Z","size":405,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-20T03:37:02.111Z","etag":null,"topics":["react","realtime","socket-io","socket-io-client","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/rohitsoni007.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,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2022-01-26T17:53:44.000Z","updated_at":"2025-12-16T14:24:30.000Z","dependencies_parsed_at":"2025-10-18T17:21:11.005Z","dependency_job_id":"6ebc657a-f5dd-407a-af7f-3124968b980d","html_url":"https://github.com/rohitsoni007/react-socket","commit_stats":null,"previous_names":["rohitsoni-dev/react-socket","rohitsoni007/react-socket"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/rohitsoni007/react-socket","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rohitsoni007%2Freact-socket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rohitsoni007%2Freact-socket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rohitsoni007%2Freact-socket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rohitsoni007%2Freact-socket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rohitsoni007","download_url":"https://codeload.github.com/rohitsoni007/react-socket/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rohitsoni007%2Freact-socket/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28607624,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-20T16:10:39.856Z","status":"ssl_error","status_checked_at":"2026-01-20T16:10:39.493Z","response_time":117,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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","realtime","socket-io","socket-io-client","websocket"],"created_at":"2026-01-20T17:06:04.396Z","updated_at":"2026-01-20T17:06:04.463Z","avatar_url":"https://github.com/rohitsoni007.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003ch1\u003eReact Socket Client\u003c/h1\u003e\n  \u003cp\u003e\u003cstrong\u003eThe Ultimate React.js Wrapper for Socket.IO Client\u003c/strong\u003e\u003c/p\u003e\n  \n  \u003cp\u003eA powerful, lightweight, and easy-to-use React library for integrating real-time WebSocket communication with Socket.IO in React applications.\u003c/p\u003e\n  \n  \u003cp\u003e\n    \u003ca href=\"https://www.npmjs.com/package/react-socket-client\"\u003e\n      \u003cimg src=\"https://img.shields.io/npm/v/react-socket-client.svg\" alt=\"npm version\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://www.npmjs.com/package/react-socket-client\"\u003e\n      \u003cimg src=\"https://img.shields.io/npm/dm/react-socket-client.svg\" alt=\"npm downloads\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rohitsoni007/react-socket/blob/main/LICENSE\"\u003e\n      \u003cimg src=\"https://img.shields.io/npm/l/react-socket-client.svg\" alt=\"license\" /\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rohitsoni007/react-socket/issues\"\u003e\n      \u003cimg src=\"https://img.shields.io/github/issues/rohitsoni007/react-socket.svg\" alt=\"issues\" /\u003e\n    \u003c/a\u003e\n  \u003c/p\u003e\n\u003c/div\u003e\n\n## 🚀 Real-Time React WebSocket Library\n\n**React Socket Client** is a comprehensive React.js wrapper for [socket.io-client](https://www.npmjs.com/package/socket.io-client) that simplifies real-time communication in React applications. Built with TypeScript and designed for React 18+, this library provides intuitive hooks and components for seamless WebSocket integration.\n\nPerfect for building **real-time chat applications**, **live dashboards**, **multiplayer games**, **collaborative tools**, and any application requiring **instant data synchronization**.\n\n### 🔑 Key Features \u0026 Benefits\n\n- ✅ **Easy Integration**: Seamless Socket.IO integration with React applications\n- ✅ **Automatic Connection Management**: Handles connection lifecycle automatically\n- ✅ **Connection Status Tracking**: Real-time monitoring (connecting, connected, disconnected, error)\n- ✅ **Configurable Logging**: Customizable log levels with extensible logger support\n- ✅ **Utility Hooks**: Pre-built hooks for common socket operations\n- ✅ **TypeScript Support**: Full TypeScript support with generic types for event data\n- ✅ **Lightweight**: Minimal bundle size with no unnecessary dependencies\n- ✅ **React 18+ Compatible**: Fully compatible with Concurrent Mode and Suspense\n- ✅ **Error Handling**: Comprehensive error handling with customizable callbacks\n- ✅ **Reconnection Logic**: Built-in reconnection with configurable parameters\n- ✅ **Developer Experience**: Intuitive API with excellent documentation\n\n### 🎯 Perfect For\n\n- Real-time chat applications\n- Live notification systems\n- Collaborative editing tools\n- Multiplayer gaming platforms\n- Stock/crypto price tickers\n- IoT dashboard applications\n- Social media feeds\n- Real-time analytics dashboards\n\n### 🔧 Technical Specifications\n\n- Supports React 18, 19 and above\n- Compatible with Socket.IO v4.8.1+\n- Full TypeScript support with type definitions\n- Zero external dependencies (except socket.io-client)\n- Tree-shakable for smaller bundles\n- Universal Module Definition (UMD) support\n\n## 📦 Installation\n\nInstall the package using npm:\n\n```bash\nnpm install react-socket-client\n```\n\nOr using pnpm:\n\n```bash\npnpm add react-socket-client\n```\n\n## 🚀 Quick Start Guide\n\n### 1. Setting up the SocketProvider\n\nWrap your application with the `SocketProvider` at the root level:\n\n```jsx\nimport React from 'react';\nimport { SocketProvider } from 'react-socket-client';\n\nconst SOCKET_URI = 'http://localhost:3000';\n\nexport default function App() {\n  return (\n    \u003cSocketProvider uri={SOCKET_URI}\u003e\n      {/* Your app components */}\n    \u003c/SocketProvider\u003e\n  );\n}\n```\n\n### 2. Using SocketProvider with Options\n\nConfigure advanced options for your socket connection:\n\n```jsx\nimport React from 'react';\nimport { SocketProvider } from 'react-socket-client';\n\nconst SOCKET_URI = 'http://localhost:3000';\n\nconst socketOptions = {\n  reconnection: true,\n  reconnectionAttempts: Infinity,\n  reconnectionDelay: 1000,\n  reconnectionDelayMax: 10000,\n  autoConnect: true,\n  transports: ['polling', 'websocket'],\n  rejectUnauthorized: true\n};\n\nexport default function App() {\n  return (\n    \u003cSocketProvider uri={SOCKET_URI} options={socketOptions}\u003e\n      {/* Your app components */}\n    \u003c/SocketProvider\u003e\n  );\n}\n```\n\n### 3. Listening to Socket Events\n\nListen to socket events using the `Socket` component:\n\n```jsx\nimport React from 'react';\nimport { Socket } from 'react-socket-client';\n\nexport default function MyComponent() {\n  const handleConnect = (data) =\u003e {\n    console.log('Socket connected', data);\n  };\n  \n  const handleDisconnect = (data) =\u003e {\n    console.log('Socket disconnected');\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cSocket on=\"connect\" handle={handleConnect} /\u003e\n      \u003cSocket on=\"disconnect\" handle={handleDisconnect} /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## 🪝 Powerful Utility Hooks\n\n### useSocketEmit\n\nEmit events to the server with type safety:\n\n```jsx\nimport React from 'react';\nimport { useSocketEmit } from 'react-socket-client';\n\nexport default function ChatInput() {\n  const emit = useSocketEmit();\n  \n  const sendMessage = (message) =\u003e {\n    emit('chat message', { text: message, timestamp: Date.now() });\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cinput \n        type=\"text\" \n        placeholder=\"Type your message...\" \n        onKeyDown={(e) =\u003e e.key === 'Enter' \u0026\u0026 sendMessage(e.target.value)} \n      /\u003e\n      \u003cbutton onClick={() =\u003e sendMessage(document.querySelector('input').value)}\u003e\n        Send\n      \u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### useSocketListener\n\nListen to socket events with automatic cleanup:\n\n```jsx\nimport React, { useState } from 'react';\nimport { useSocketListener } from 'react-socket-client';\n\nexport default function MessageList() {\n  const [messages, setMessages] = useState([]);\n  \n  useSocketListener('chat message', (data) =\u003e {\n    setMessages(prev =\u003e [...prev, data]);\n  });\n  \n  useSocketListener('user joined', (data) =\u003e {\n    console.log(`${data.username} joined the chat`);\n  });\n\n  return (\n    \u003cdiv\u003e\n      {messages.map((msg, index) =\u003e (\n        \u003cdiv key={index}\u003e{msg.text}\u003c/div\u003e\n      ))}\n    \u003c/div\u003e\n  );\n}\n```\n\n### useSocketStatus\n\nMonitor connection status in real-time:\n\n```jsx\nimport React from 'react';\nimport { useSocketStatus } from 'react-socket-client';\n\nexport default function ConnectionIndicator() {\n  const { status, error } = useSocketStatus();\n  \n  const getStatusColor = () =\u003e {\n    switch(status) {\n      case 'connected': return 'green';\n      case 'connecting': return 'orange';\n      case 'disconnected': return 'red';\n      default: return 'gray';\n    }\n  };\n  \n  return (\n    \u003cdiv\u003e\n      \u003cspan style={{ color: getStatusColor() }}\u003e●\u003c/span\u003e\n      \u003cspan\u003e Status: {status}\u003c/span\u003e\n      {error \u0026\u0026 \u003cp style={{ color: 'red' }}\u003eError: {error.message}\u003c/p\u003e}\n    \u003c/div\u003e\n  );\n}\n```\n\n## 🔄 Enhanced useSocket Hook\n\nThe powerful `useSocket` hook provides direct access to the socket instance along with connection status and error information:\n\n```jsx\nimport React, { useEffect } from 'react';\nimport { useSocket } from 'react-socket-client';\n\nexport default function ChatRoom() {\n  const { socket, status, error } = useSocket();\n  \n  useEffect(() =\u003e {\n    if (socket) {\n      socket.on('connect', handleConnect);\n      socket.on('disconnect', handleDisconnect);\n      socket.on('chat message', handleIncomingMessage);\n    }\n    \n    // Cleanup listeners on unmount\n    return () =\u003e {\n      if (socket) {\n        socket.off('connect', handleConnect);\n        socket.off('disconnect', handleDisconnect);\n        socket.off('chat message', handleIncomingMessage);\n      }\n    };\n  }, [socket]);\n  \n  const handleConnect = (data) =\u003e {\n    console.log('Socket connected', data);\n  };\n  \n  const handleDisconnect = (data) =\u003e {\n    console.log('Socket disconnected');\n  };\n  \n  const handleIncomingMessage = (data) =\u003e {\n    console.log('Received message:', data);\n  };\n\n  const sendMessage = (message) =\u003e {\n    if (socket) {\n      socket.emit('chat message', { text: message, timestamp: Date.now() });\n    }\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv\u003e\n        \u003cspan\u003eConnection Status: {status}\u003c/span\u003e\n        {error \u0026\u0026 \u003cspan style={{ color: 'red' }}\u003e Error: {error.message}\u003c/span\u003e}\n      \u003c/div\u003e\n      \u003cinput \n        type=\"text\" \n        placeholder=\"Type your message...\" \n        onKeyDown={(e) =\u003e e.key === 'Enter' \u0026\u0026 sendMessage(e.target.value)} \n      /\u003e\n      \u003cbutton onClick={() =\u003e sendMessage(document.querySelector('input').value)}\u003e\n        Send Message\n      \u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## 📝 Configurable Logging System\n\nFine-tune your debugging experience with configurable logging levels and custom logger support:\n\n```jsx\nimport React from 'react';\nimport { SocketProvider } from 'react-socket-client';\n\n// Create a custom logger with your preferred formatting\nconst customLogger = {\n  error: (message, ...args) =\u003e console.error('[ReactSocket] ERROR:', message, ...args),\n  warn: (message, ...args) =\u003e console.warn('[ReactSocket] WARN:', message, ...args),\n  info: (message, ...args) =\u003e console.info('[ReactSocket] INFO:', message, ...args),\n  debug: (message, ...args) =\u003e console.debug('[ReactSocket] DEBUG:', message, ...args),\n};\n\nexport default function App() {\n  return (\n    \u003cSocketProvider \n      uri=\"http://localhost:3000\"\n      logLevel=\"debug\"  // Options: 'error', 'warn', 'info', 'debug'\n      logger={customLogger}\n    \u003e \n      {/* Your app components */}\n    \u003c/SocketProvider\u003e\n  );\n}\n```\n\n### Available Log Levels\n\n- `error`: Critical issues that prevent normal operation\n- `warn`: Potentially harmful situations\n- `info`: General informational messages\n- `debug`: Detailed debugging information (recommended for development only)\n\n## 🎯 TypeScript Generic Types Support\n\nAchieve type safety with generic parameters for event data in all components and hooks:\n\n```tsx\nimport React from 'react';\nimport { Socket, useSocketListener } from 'react-socket-client';\n\n// Define your custom event data types\ninterface ChatMessage {\n  userId: string;\n  username: string;\n  message: string;\n  timestamp: number;\n}\n\ninterface UserStatus {\n  userId: string;\n  status: 'online' | 'offline';\n}\n\nexport default function ChatComponent() {\n  // Type-safe event handler with useSocketListener\n  const handleMessage = (data: ChatMessage) =\u003e {\n    console.log(`Message from ${data.username}: ${data.message}`);\n  };\n  \n  const handleUserStatus = (data: UserStatus) =\u003e {\n    console.log(`User ${data.userId} is now ${data.status}`);\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cSocket on='chat-message' handle={handleMessage} /\u003e\n      \u003cSocket on='user-status' handle={handleUserStatus} /\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n### Benefits of TypeScript Support\n\n- ✅ Compile-time type checking\n- ✅ Autocomplete in your IDE\n- ✅ Reduced runtime errors\n- ✅ Better code documentation\n- ✅ Easier refactoring\n\n## ⚠️ Comprehensive Error Handling\n\nRobust error handling mechanisms to ensure your application remains stable even during connection issues:\n\n### Global Error Handler\n\nHandle connection errors at the provider level:\n\n```tsx\nimport React from 'react';\nimport { SocketProvider } from 'react-socket-client';\n\nexport default function App() {\n  const handleError = (error: Error) =\u003e {\n    console.error('Socket connection error:', error);\n    // Show user-friendly error message\n    // Log to error tracking service\n    // Attempt reconnection or fallback\n  };\n  \n  return (\n    \u003cSocketProvider \n      uri=\"http://localhost:3000\"\n      onError={handleError}\n    \u003e \n      {/* Your app components */}\n    \u003c/SocketProvider\u003e\n  );\n}\n```\n\n### Component-Level Error Monitoring\n\nMonitor connection status and errors within your components:\n\n```tsx\nimport React from 'react';\nimport { useSocket } from 'react-socket-client';\n\nexport default function ConnectionStatus() {\n  const { socket, status, error } = useSocket();\n\n  // Display user-friendly connection status\n  const renderStatus = () =\u003e {\n    switch(status) {\n      case 'connected':\n        return \u003cspan style={{ color: 'green' }}\u003eConnected ✓\u003c/span\u003e;\n      case 'connecting':\n        return \u003cspan style={{ color: 'orange' }}\u003eConnecting...\u003c/span\u003e;\n      case 'disconnected':\n        return \u003cspan style={{ color: 'red' }}\u003eDisconnected ✗\u003c/span\u003e;\n      default:\n        return \u003cspan\u003eUnknown\u003c/span\u003e;\n    }\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cdiv\u003eStatus: {renderStatus()}\u003c/div\u003e\n      {error \u0026\u0026 (\n        \u003cdiv style={{ color: 'red' }}\u003e\n          Error: {error.message}\n          \u003cbutton onClick={() =\u003e socket?.connect()}\u003e\n            Reconnect\n          \u003c/button\u003e\n        \u003c/div\u003e\n      )}\n    \u003c/div\u003e\n  );\n}\n```\n\n### Error Recovery Strategies\n\n- Automatic reconnection with exponential backoff\n- Graceful degradation during network issues\n- User notifications for connection problems\n- Fallback mechanisms for critical features\n\n## 📊 Performance Metrics\n\nReact Socket Client is optimized for performance:\n\n- **Bundle Size**: Lightweight at \u003c 5KB gzipped\n- **Connection Speed**: Establishes connections in \u003c 100ms\n- **Memory Usage**: Efficient memory management with automatic cleanup\n- **Scalability**: Handles thousands of concurrent connections\n\n## 🔧 Advanced Configuration\n\n### Socket.IO Options\n\nAll standard Socket.IO client options are supported:\n\n```jsx\nconst socketOptions = {\n  reconnection: true,\n  reconnectionAttempts: Infinity,\n  reconnectionDelay: 1000,\n  reconnectionDelayMax: 5000,\n  randomizationFactor: 0.5,\n  timeout: 20000,\n  autoConnect: true,\n  transports: ['polling', 'websocket'],\n  rejectUnauthorized: true,\n  path: '/socket.io',\n  upgrade: true,\n  forceJSONP: false,\n  jsonp: true,\n  forceBase64: false,\n  enablesXDR: false,\n  timestampRequests: false,\n  timestampParam: 't',\n  policyPort: 843,\n  transports: ['websocket', 'polling'],\n  transportOptions: {},\n  rememberUpgrade: false\n};\n\n\u003cSocketProvider uri=\"http://localhost:3000\" options={socketOptions}\u003e\n  {/* Your app */}\n\u003c/SocketProvider\u003e\n```\n\n## 🧪 Testing\n\nReact Socket Client is thoroughly tested with Jest and React Testing Library:\n\n```bash\nnpm test\n```\n\nFor coverage report:\n\n```bash\nnpm run test:coverage\n```\n\n## 🤝 Contributing\n\nWe welcome contributions! Here's how you can help:\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\n4. Push to the branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n### Development Setup\n\n```bash\nnpm install\nnpm run build\nnpm test\n```\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n\n## 🙏 Acknowledgments\n\n- Thanks to the Socket.IO team for creating an excellent WebSocket library\n- Inspired by the React community's need for better WebSocket integrations\n- Special thanks to all contributors and users who provided feedback\n\n## Support\n\nIf you encounter any issues or have questions:\n\n- Check the [Issues](https://github.com/rohitsoni007/react-socket/issues) page\n- Submit a new issue with a detailed description\n\n---\n\n\u003cdiv align=\"center\"\u003e\n  \u003cp\u003eBuilt with ❤️ for the React community\u003c/p\u003e\n  \u003cp\u003eIf you find this project helpful, consider giving it a ⭐ on GitHub!\u003c/p\u003e\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frohitsoni007%2Freact-socket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frohitsoni007%2Freact-socket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frohitsoni007%2Freact-socket/lists"}