How to Use Globally in Multiple Client React Components

How can we use across our client application without having to import in every component?

Disclaimer: this isn’t actually a solution that exposes the socket instance globally, as you’d expect in the technical sense. The socket is simply available to be imported by all components.

Suppose we have an Express server set up to handle socket connections.

We have a single handler for an event called messageFromClient, which will print a message to console. It will then send back the message Thank you for the message! using the messageFromServer event.

// server/index.ts
import express from "express";
import http from "http";
import { Server } from "";

const app = express();
const server = http.createServer(app);
const io = new Server(server);

io.on("connection", (socket) => {
  socket.on("messageFromClient", (message) => {
    console.log(message);"messageFromServer", "Thank you for the message!");

On the client side, we want to set up a Socket.js file accessible by all components.

We can then set up a default export of the socket instance using io(), passing in the server URL.

// client/Socket.js
import io from "";
const ENDPOINT = 'http://localhost:5000';
export default io(ENDPOINT);

Finally, inside any client component, we can import this socket and send/receive events.

// client/Component1.js
import socket from './Socket';
const doSomething = () => {
  socket.emit("messageFromClient", "Hi!");
  socket.on("messageFromServer", message => console.log(message));