Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda