Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
Updating component state by Listening to socket events inside react hooks or handling them inside middleware? what are the downsides of each one?

I have a socket class for dispatching and listening to events from the server.

The class has a method for synchronizing state between server and client.

here is how I listen to changes or events from the server.

import React, { useEffect, useState } from 'react'
import { useStore } from "./store"; // this is a zustand store object
import Game from "./game";

export const Lobby = ({ user }) => {
    const players = useStore(state => state.players);

    const dispatch = useStore(state => state.dispatch)


    const addPlayer = (player) => {
        dispatch({ type: "NEW_PLAYER", player })
    }

    useEffect(() => {
        // inside Game -> this.eventListeners[key].push(cb)
        Game.register('new-palyer', addPlayer); 
       
    }, [])

    return (
        <div>
            {
                players.map(player => <span>{player.name}</span>)
            }
        </div>
    )
}

There is another way by subscription to the store inside the Game class and updating the store with any changes. I do not implement any but before any changes to the current structure of these listeners and dispatchers, I need to make a better decision by listing the pros and cons of each paradigm. I appreciate it if answered by the real example of the middleware paradigm.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Most socket has their own event listener. For example, this is how Primus client listener works:

primus.on('data', function (data) {
  if (primus.reserved(data.args[0])) return;

  primus.emit.apply(primus, data.args);
})

I assume your socket has this kind of listener too. The best way to sync downstream data, i.e: server to client, is in that handler. But for upstream data update, i.e: client to server, just put the handler on component like your code snippet.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!