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?
CodePudding user response:
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.
CodePudding user response:
Maybe you should try Redux to manage state and use a store to manage the state of game.