TransWikia.com

How to share state between users in ReactJS

Stack Overflow Asked on November 15, 2021

I’m building a multiplayer card game mainly in ReactJS and want to share some state between users (players). I need each user to be able to know when it’s their turn to play and see some things about other users like score and current number of cards in hand, etc. For example, when one player’s turn ends, I need the next player’s app to recognize it’s their turn and provide the applicable options.

It seems WebSockets or something based on it would be a good option. I’m still learning React and other pieces so I’m trying to keep the number of technologies down for now. I’m considering setting up rapid polling (every 200 ms, perhaps), either to an API or maybe checking against a file on the server or database entries.

Are there especially concerning performance issues or better options to get it working? I’m also learning about AWS and Docker and intend to host on AWS, if possible.

4 Answers

WebSockets won't work for you as you need one fixed party in WebSocket connection.

You could share the state peer-to-peer style with a WebRTC connection and using the DataChannel in that connection, but that's not an easy task. (see for example: https://www.html5rocks.com/en/tutorials/webrtc/basics/#toc-rtcdatachannel)

The much more common option is to use a central data storage and either sync your state with that or just store it there in the first place. You could use Firebase (see answer by David) or any other kind of database. Firebase is particularly easy to set up, though.

If you have/need/want to use an API-backend anyways, you can use pretty much any kind of database layer in that and just talk REST or GraphQL with the API to share your state between players.

Answered by Mastacheata on November 15, 2021

instead of sharing state between players you should explore the possibility of players sharing an instance of game object on the server.

for example :

game={
status:'running',
players:2,
p1:{state:'waiting'},
p2:{state:'active'}
}
  • time complexity for common state on server will be [n]

  • expected time complexity for state exchange or polling is [n^2] or more.

Answered by nikhil swami on November 15, 2021

If you want to try serverless approach, you can look at AWS Lambda and Dynamo DB.

Answered by bodoroman on November 15, 2021

I recommend you use firebase which is a database to send and receive data online because the states of react js are not interlaced between devices

Answered by David on November 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP