Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

178
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda