Huzaifa Rasheed

Huzaifa Rasheed

Software Engineer


How to abstract Socket.IO connections in your SPA.

Posted on February 10, 2022

Repost of

When working with socketIO client in your SPA, it may become very hard to manage the socket instance, events emitters, and work with the callbacks in different places of the app. Especially when there are multiple different servers to connect with. What can be done?


We can create a closure that takes event callbacks as functions and return event emitters, to abstract socketIO implementation in a single file (let’s call it SocketManager.js).


import io from "";

const SocketManager = ({
  onCallback = () => {},
}) => {
  const socket = io(/* server url to connect */);

  // Callbacks
  socket.on('callback-event-name', (payload) => {
    onCallback && onCallback(payload);

  // Emitters
  const emitEvent = (eventPayload) => {
    socket.emit('emit-event-name', eventPayload);

  return {

export default SocketManager;

then we can use this in our React code like this

import React from "react";
import SocketManager from "./SocketManager.js";

const SocketConsumer = () => {
  const { emitEvent } = SocketManager({
    onCallback: handleCallback,

  const handleCallback = (payload) => {
    /** Do something with the payload */

  return <button onClick={emitEvent}>Fire Event</button>;

export default SocketConsumer;

Hope this helps you in your projects. Thanks 🙂