"Socket in react js with sepreate file"
Bootstrap 4.1.1 Snippet by Arjunverma

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container"> <div class="row"> <h2>Socket in react js with sepreate file</h2> </div> </div> <!--create socket folder/socket.js file--> // socket.js import { io } from "socket.io-client"; // Create and export the socket instance const socket = io('http://localhost:2200', { transports: ['websocket'], // Use WebSocket as transport (optional) autoConnect: false, // Prevent auto-connect for better control }); // Export the socket for use in other components export default socket; File 1 >>>>>>>>>
<!--create socket folder/useSocket.js file to handle connection and disconnect--> import { useEffect } from 'react'; import socket from './socket'; const useSocket = () => { useEffect(() => { // Connect to the server when the component mounts socket.connect(); // Clean up on component unmount return () => { if (socket.connect) { socket.disconnect(); } }; }, []); }; export default useSocket; File 2 >>>>>>>
/*Then use in any component in useEffect*/ import { useEffect, useState } from 'react' import reactLogo from './assets/react.svg' import viteLogo from '/vite.svg' import './App.css' import { BrowserRouter as Router, Routes, Route } from 'react-router-dom' import Navbar from './pages/Navbar' import Home from './pages/Home' import PrivateRoute from './auth/PrivateRoute' import PrivatePage from './pages/PrivatePage' import socket from './sockets/socket' import useSocket from './sockets/useSocket' function App() { useSocket() // Automatic handle connect and disconnect useEffect(() => { // socket.connect() // Listen for the "connect" acknowledgment socket.on('connect', () => { console.log('Connected to the server:', socket.id); }); // Emit a "online" event to the server socket.emit('online', { user: 'Arjun' }); }, []); return ( <> <Router> <Navbar /> <Routes> <Route path='/' element={<Home />} /> <Route path='/private' element={<PrivateRoute> <PrivatePage /></PrivateRoute>} /> </Routes> </Router> </> ) } export default App

Related: See More


Questions / Comments: