Updating React Component state Dynamically based on server state

I have a component that shows no of players logged in as soon as the component loads.

function PlayerList({gamePin}){
const [playerList, setPlayerList] = useState("");
useEffect( ()=>{
    axios.get("http://localhost:8080/game/lobby/"+gamePin)
         .then( response =>{
             setPlayerList(response.data)
         })
})
return(
    <div className='container'>
        <div className='lobbycontainer'>
            <h1>Lobby</h1>
            <Grid container spacing={3}>
                {playerList.map(player=>{
                    <Player {PlayerName,PlayerId} />
                })}
            </Grid>
        </div>
    </div>
    )}

export default PlayerList;

This will display the name of the player who is logged in and any other players already logged into the lobby.

But my question is how do the players who are already logged in will get to know about the new players who joined.

Possible Approach

  1. Send a request with a time interval of every 2 seconds.

    setInterval(httpRequest,2000);

Is this the right way to do this? are there any alternate approaches?

How does a component dynamically update its state based on the changes in the backend? and respond to the changes by rerendering the component to reflect the changes.

98 thoughts on “Updating React Component state Dynamically based on server state”

Leave a Comment