This website uses cookies to ensure you get the best experience on our website.

Skip to content
LOGO
  • Company

    About IGNEK

    Learn about our story and our mission.

    Careers

    We're hiring!

    We always looking for talented peoples. Join our team!

    Blogs

    The latest industry news, updates and info.

    Case Studies

    Take a closer look at the projects we've delivered

    Webinar

    Watch our latest organized webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Custom Enterprise Portal Development for flawless Solutions

    Dedicated Development Team

    Expand Teams, Optimize Development with Our Expertise

    Back-end Development

    Empowering your digital presence with robust backend development expertise

    Front-end Development

    Crafting engaging user experiences through expert frontend development

    Digital Transformation

    Embrace digital transformation by modernizing process

    SaaS Development

    Transform your business with SaaS Innovative Solutions

    Technologies

    Liferay Services

    Development & Customization

    Theme

    Upgradation

    Migration

    Proof of Concept

    Performance Tunning

    Architecture

    Support & Maintenance

    E-commerce

    Expert Advice

    React Services

    Enterprise Development

    Custom Application

    Single Page Application

    Architecture

    API Integration

    Migration

    Consulting

    Maintenance & Support

    Spring Boot Services

    Web Service

    MVC Web Development

    API Integration

    Security

    Migration

    Microservices

    Support & Maintenance

    AEM Services

    Consulting Service

    Site Development

    Migration & Upgradation

    Integration

    Maintenance & Support

    Custom Solutions

    Content Management

    Team Augementation

  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Transforming industries through cutting edge SaaS solutions.

    Customer Portal : Boost Business Productivity

    Streamline operations and enhance productivity with our Customer Portal solution.

    Liferay Based Intranet Portal

    Internal portal for company communication, collaboration and resources

    Integration

    Matomo Integration with Liferay

    Integrate Matomo to enable user interactions seamlessly.

    Microsoft Teams integration with Liferay

    Integrate to enable seamless collaboration, messaging within your portal.

    Jira Integration With Liferay

    Optimizes business operations by integrating with Jira.

  • Hire Us

    Liferay

    Get expert Liferay developers for seamless portal solutions.

    React JS

    Get expert ReactJS developers for dynamic web solutions.

    Web Developer

    Get custom web solutions from IGNEK's expert developers.

    Spring Boot

    Get top-notch Spring Boot developers for your project success!

    Healthcare

    Get top Healthcare Developers for cutting-edge medical software.

    MERN Stack

    Get expert MERN developers from IGNEK for custom, innovative project solutions.

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • info@ignek.com
    • Ahmedabad, Gujarat, India – 382470
SCHEDULE CALL
  • COMPANY
    • About
    • Case Studies
    • Blogs
    • Career
    • Webinar
  • SERVICES
    • Enterprise Portal Development
    • Dedicated Development Team
    • Back-end Development
    • Front-end Development
    • Digital Transformation
    • SaaS Development
  • SOLUTION
    • Customer Portal:  Boost Business Productivity
    • SaaS : Software as a Service
    • Liferay Based Employee Intranet Portal
  • TECHNOLOGY
    • Liferay Services
      • Liferay Development and Customization
      • Liferay Theme Development Service
      • Liferay DXP 7.4 Upgrade
      • Liferay Migration
      • Liferay Proof Of Concept
      • Liferay Performance Tuning
      • Liferay Architecture Design Service
      • Liferay Support And Maintenance Service
      • Liferay Ecommerce Development
      • Liferay Expert Advice
    • ReactJS Services
      • ReactJS Enterprise Application Development
      • ReactJS Custom Application Development
      • ReactJS Single Page Application Development (SPA)
      • ReactJS Applications Architecture
      • ReactJS API Integration
      • ReactJS Migration
      • ReactJS Consulting
      • ReactJS Maintenance and Support
    • Spring Boot Services
      • Spring Boot Web Development Service
      • Spring MVC Web Development
      • Spring Boot API Integration Service
      • Spring Boot Security
      • Spring Boot Migration Service
      • Spring Boot Microservices
      • Spring Boot Support & Maintenance Service
    • AEM Development Services
      • AEM Consulting Services
      • AEM Site Development
      • AEM Migration & Upgradation
      • AEM Integration Services
      • AEM Maintenance & Support
      • AEM Content Management
      • Custom AEM Solutions
      • AEM Team Augmentation
  • INTEGRATION
  • HIRE US
    • Hire Liferay Developer
    • Hire ReactJS Developer
    • Hire Spring Boot Developer
    • Hire Healthcare Developer
    • Hire Web Developer
    • Hire MERN Stack Developer
  • CONTACT US
  • Company

    About IGNEK

    Careers

    We're hiring!

    Blogs

    Case Studies

    Webinar

    Get in touch with our HR team

    • hr@ignek.com
    • +91 93284 95160
    • Ahmedabad, Gujarat, India – 382470
  • Services

    Enterprise Portal Development

    Dedicated Development Team

    Back-end Development

    Front-end Development

    Digital Transformation

    SaaS Development

    Technologies

    Liferay Liferay Services
    • Development & Customization
    • Theme
    • Upgradation
    • Migration
    • Proof of Concept
    • Performance Tuning
    • Architecture
    • Support & Maintenance
    • E-commerce
    • Expert Advice
    React React Services
    • Enterprise Development
    • Custom Application
    • Single Page Application
    • Architecture
    • API Integration
    • Migration
    • Consulting
    • Maintenance & Support
    Spring Boot Spring Boot Services
    • Web Service
    • MVC Web Development
    • API Integration
    • Security
    • Migration
    • Microservices
    • Support & Maintenance
    AEM AEM Services
    • Consulting Service
    • Site Development
    • Migration & Upgradation
    • Integration
    • Maintenance & Support
    • Custom Solutions
    • Content Management
    • Team Augmentation
  • Solution

    Ready for digital excellence

    In our rapidly evolving world, businesses are always on the lookout for fresh ways to improve their operations and connect with their audiences.

    Contact US

    Solutions

    SaaS : Software As A Service

    Customer Portal : Boost Business Productivity

    Liferay Based Intranet Portal

    Integration

    Matomo Integration with Liferay

    Microsoft Teams integration with Liferay

    Jira Integration With Liferay

  • Hire Us

    Liferay

    React JS

    Web Developer

    Spring Boot

    Healthcare

    MERN Stack

    Why Hire Developers From IGNEK ?

    • Certified Developer
    • Transparent Communication
    • Flexible Hiring Modals
    • Fully Signed NDA
    • Cost Effective
    • Easy Exit Policy

    Get in touch with our Sales team

    • sales@ignek.com
    • +91 6351576580
    • IGNEK
    • Ahmedabad, Gujarat, India – 382470
  • SCHEDULE CALL

Sharing WebSocket Connections between Browser Tabs and Windows

  • ReactJS
  • March 28, 2025

Share On :

Introduction

WebSocket connections are special communication channels that allow web browsers and servers to talk to each other in real-time. When you have multiple tabs or windows open in your browser, each one establishes its own WebSocket connection. This can be wasteful and affect the performance of your web application.

A better approach is to share a single WebSocket connection across all open tabs and windows. In this blog post, we’ll explore how to achieve this using BroadcastChannel and SharedWorker.

Why Share WebSocket Connections?

When multiple tabs create separate WebSocket connections, it can lead to:

  • Increased server load : Multiple connections mean multiple active sockets on the server.
  • Unnecessary network traffic : Each tab sends and receives duplicate data.
  • Higher resource consumption : More connections mean higher CPU and memory usage.

By sharing a WebSocket connection, we reduce overhead, improve performance, and ensure a smoother user experience.

Frontend Setup in React

Let’s create a React app using the following command:

				
					//Create a react app using the following command
npm create vite@latest my-websocket-app  --template react
cd  my-websocket-app
npm install 

//Command for run the React project
npm run dev


				
			
Solution 1 : Using BroadcastChannel in React.js

The BroadcastChannel API allows communication between different tabs of the same origin. We can use it to create a single WebSocket connection in one tab and share data with others.

Implementation

1. Create a WebSocket Context in React

We will use React’s Context API to manage the WebSocket connection and share it across components.

				
					// WebSocketContext.jsx

import React, { createContext, useEffect, useState } from "react";

export const WebSocketContext = createContext(null);
const channel = new BroadcastChannel("websocket_channel");

export const WebSocketProvider = ({ children }) => {
  const [messages, setMessages] = useState([]);
  let socket = null;

  useEffect(() => {
    function connectWebSocket() {
      socket = new WebSocket("wss://your-websocket-server.com");  // Replace with actual WebSocket URL
      socket.onopen = () => {
        console.log("WebSocket connected");
        channel.postMessage({ type: "connected" });
      };

      socket.onmessage = (event) => {
        const message = event.data;
        setMessages((prev) => [...prev, message]);
        channel.postMessage({ type: "message", data: message });
      };

      socket.onclose = () => {
        console.log("WebSocket closed, reconnecting...");
        setTimeout(connectWebSocket, 3000);
      };
    }

    connectWebSocket();

    channel.onmessage = (event) => {
      if (event.data.type === "message") {
        setMessages((prev) => [...prev, event.data.data]);
      }
    };
  }, [ ]);

  return (
    <WebSocketContext.Provider value={{ messages }}>
      {children}
    </WebSocketContext.Provider>
  );
};

				
			

2. Use the WebSocket Context in a Component

We can now use the WebSocket context in any React component to access the shared WebSocket messages.

				
					// ChatComponent.jsx
import React, { useContext } from "react";
import { WebSocketContext } from "./WebSocketContext";

const ChatComponent = () => {
  const { messages } = useContext(WebSocketContext);

  return (
    <div>
      <h2>Messages</h2>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
    </div>
  );
};

export default ChatComponent;    

				
			

3. Wrap Your App with WebSocketProvider

To ensure all components can access the WebSocket, wrap your application with WebSocketProvider.

				
					// App.jsx
import React from "react";
import { WebSocketProvider } from "./WebSocketContext";
import ChatComponent from "./ChatComponent";

function App() {
  return (
    <WebSocketProvider>
      <ChatComponent />
    </WebSocketProvider>
  );
}

export default App;  

				
			
Solution 2 : Using SharedWorker in React.js

A SharedWorker runs in the background and can be used by multiple browser tabs to share a WebSocket connection.

Implementation

1. Create a SharedWorker script

				
					// sharedWorker.js
self.onconnect = function (event) {
  const port = event.ports[0];
  let socket = new WebSocket("wss://your-websocket-server.com");

  socket.onopen = () => {
    console.log("WebSocket connected");
  };

  socket.onmessage = (event) => {
    port.postMessage(event.data);
  };

  socket.onclose = () => {
    console.log("WebSocket closed, reconnecting...");
    setTimeout(() => {
      socket = new WebSocket("wss://your-websocket-server.com");
    }, 3000);
  };

  port.onmessage = (event) => {
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(event.data);
    }
  };
};


				
			

2. Use the SharedWorker in a React Component

				
					// useSharedWorker.jsx
import { useEffect, useState } from "react";

export function useSharedWorker() {
  const [messages, setMessages] = useState([]);
  const worker = new SharedWorker("sharedWorker.js");
  worker.port.start();

  useEffect(() => {
    worker.port.onmessage = (event) => {
      setMessages((prev) => [...prev, event.data]);
    };
  }, [ ]);

  function sendMessage(message) {
    worker.port.postMessage(message);
  }

  return { messages, sendMessage };
}
;


				
			

3. Use it in a React Component

				
					// ChatComponentWithWorker.jsx
import React from "react";
import { useSharedWorker } from "./useSharedWorker";

const ChatComponentWithWorker = () => {
  const { messages, sendMessage } = useSharedWorker();

  return (
    <div>
      <h2>Messages</h2>
      <ul>
        {messages.map((msg, index) => (
          <li key={index}>{msg}</li>
        ))}
      </ul>
      <button onClick={() => sendMessage("Hello from tab!")}>Send Message</button>
    </div>
  );
};

export default ChatComponentWithWorker;


				
			
Conclusion

By using BroadcastChannel and SharedWorker in a React.js application, we can efficiently share a single WebSocket connection across multiple tabs. BroadcastChannel is simple and works well for message sharing, while SharedWorker provides a persistent background process for better control.

Choose the approach that best fits your use case and optimize WebSocket usage in your React applications.

Explore Our Services

Discover how we can help your business thrive, whether you’re running a small startup, an SME, or a large enterprise. We’re here to understand your unique needs and goals, offering the expertise and resources to support your journey to success.
Stay informed about our React services and updates by subscribing to our newsletter—just fill in the details below to subscribe.

Loading
Loading...

Related Blogs

September 23, 2024
Custom Element using Client Extension
Custom Element Using Client Extension
March 3, 2025
Implement Infinite Scrolling in React by using Intersection Observers API
Implement Infinite Scrolling in React by using Intersection Observers API
March 12, 2025
Implementing backend pagination with Material-UI in React
Implementing backend pagination with Material-UI in React
Loading...

Featured Projects Portfolios

October 3, 2023
Streamlining Global Communication with a Unified Digital Platform
Streamlining Global Communication with a Unified Digital Platform
March 21, 2024
EPF Government Enterprise Website _ Multilingual, Access for Member, Employer, Corporate - New
EPF Government Enterprise Website : Multilingual, Access for Member, Employer, Corporate
June 19, 2024
Music License Management Portal _ Onboarding & Data Integrity
Music License Management Portal : Onboarding & Data Integrity

Digital Solutions for Your Business with IGNEK

4.9

5.0

5.0

5.0

LOGO

Making the world a better place through constructing elegant hierarchies

COMPANY

  • About
  • Career
  • Case Study
  • Blogs

SERVICES

  • Enterprise Portal Development
  • Dedicated Development Team
  • Back-end Development
  • Front-end Development
  • Digital Transformation
  • SaaS Development

HIRE US

  • Liferay
  • Spring Boot
  • ReactJS
  • Healthcare
  • MERN Stack
  • AEM

CONTACT

  • info@ignek.com
  • info@ignek.com
SALES
  • sales@ignek.com
  • (+91) 635 157 6580
CAREER
  • hr@ignek.com
  • (+91) 932 849 5160
  • E 910-912, Ganesh Glory 11, Jagatpur Road, SG Highway, Ahmedabad, Gujarat - 382470

© 2018-2025 IGNEK, Inc. All rights reserved

Linkedin Facebook X-twitter Instagram