1

I have this very large Game object that completely determines the state of the Game, including data that gets rendered and data that does not get rendered. Its nested values are very frequently changed.

Should I store this very large object in a state...

const [game, setGame] = useState(new Game()) // Very large Game object

and use setGame with each little update to the game? For example,

function playerDamage(dmg) {
  const nextState = game.copy();
  nextState.player.health -= dmg;
  setGame(nextState);
}

It seems to me that it would be extremely inefficient to make a copy of Game and use setGame with every little change to Game. Am I correct in this assumption, or does React and TS/JS handle this well "under the hood"?

I guess to rephrase this question: what's the best way to frequently update deeply nested values in a React state object?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Andres Holguin
  • 173
  • 1
  • 6

2 Answers2

2

Maybe you should try Redux to manage state and use a store to manage the state of game.

https://react-redux.js.org/

1

Yes, your current approach could well be pretty inefficient if you copy the whole object:

const nextState = game.copy();

If the game is that large, making such a deep copy frequently could be an issue. But, for this particular situation, there's a simple solution: don't copy the whole thing, only copy the objects that need to be changed. There are only two objects that need to be changed (plus the new final outer state object), so only change those, instead of recursively copying everything.

function playerDamage(dmg) {
  setGame({
    ...game,
    player: {
      ...game.player,
      health: game.player.health - dmg
    }
  });
}

This version of the playerDamage function would be quite cheap.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Does this perform well even when `game` is really big? The spread operator won't slow down the processing? – Olle Härstedt Nov 10 '22 at 23:30
  • 1
    It won't slow down anything unless there are an unreasonably huge number of properties in `game`, such as tens of thousands, and even then, it'll probably be unnoticeable unless it's running inside a tight loop. – CertainPerformance Nov 10 '22 at 23:31
  • Hm, good point. Here's another thread on the spread operator performance, btw: https://stackoverflow.com/questions/55843097/does-spread-operator-affect-performance – Olle Härstedt Nov 10 '22 at 23:32