DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

useSocket

If you're using socket.io-client in your React application, you can create a custom hook that encapsulates the connection, event listening, and message emitting logic in a neat and reusable manner. Socket.IO provides some advanced features over plain WebSockets, like automatic reconnection, event-based communication, rooms, etc., which can be efficiently managed within a custom hook.

Here's an example of how you could implement a custom hook, useSocket, for a React application using socket.io-client:

import { useEffect, useRef, useState, useCallback } from 'react';
import io from 'socket.io-client';

function useSocket(url, options) {
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    // Initialize socket connection
    const socketIo = io(url, options);

    setSocket(socketIo);

    return () => {
      socketIo.disconnect();
    };
  }, [url, options]);

  // Function to emit messages
  const emit = useCallback((event, data) => {
    if (socket) {
      socket.emit(event, data);
    }
  }, [socket]);

  // Function to subscribe to an event
  const on = useCallback((event, func) => {
    if (socket) {
      socket.on(event, func);

      return () => socket.off(event, func); // Return a cleanup function
    }
  }, [socket]);

  return { socket, emit, on };
}

export default useSocket;
Enter fullscreen mode Exit fullscreen mode

How to Use the useSocket Hook in Your Components:

  1. Connecting and Listening for Events: To connect to the socket server and listen for events, simply invoke the useSocket hook with the server URL. You can use the on function returned by the hook to listen for specific events.
import React, { useEffect } from 'react';
import useSocket from './useSocket';

function ChatComponent() {
  const { emit, on } = useSocket('http://localhost:3000');

  useEffect(() => {
    // Subscribe to an event
    const unsubscribe = on('chat message', (msg) => {
      console.log('New message:', msg);
    });

    // Cleanup subscription on component unmount
    return unsubscribe;
  }, [on]);

  const sendMessage = () => {
    emit('chat message', 'Hello World!');
  };

  return <button onClick={sendMessage}>Send Message</button>;
}

export default ChatComponent;
Enter fullscreen mode Exit fullscreen mode
  1. Emitting Messages: Use the emit function returned by the hook to send messages or data to the server. It's designed to mimic the Socket.IO client's emit method, taking an event name as the first argument and the data to send as the second.

This implementation ensures that your components remain clean and focused on their primary function, abstracting away the complexity of managing Socket.IO connections and event listeners. The useSocket hook can be further customized and extended based on your specific requirements, such as handling reconnections explicitly, managing socket instance state more granularly, or incorporating additional Socket.IO features.

Top comments (0)