What are the disadvantages of mutating state in reagent?

I have a React app with a top level component and a number of nested subcomponents. The top-level component is the only stateful component. This state takes the form of a single variable:

this.state = {
  g: new BlackJackGame()
}

      

g contains a complex data structure:

class BlackJackGame{
   playerHand = []; 
   dealerHand = [];
   deck = [ /* initially 52 cards * ]; 
   ....
}

      

g also contains three methods that mutate its state in place:

g.deal(): take 4 cards from deck and add them to playerHand and dealerHand (2 cards each)
g.hit(): take 1 card from deck and add it to playerHand
g.stay(): take cards from deck and add to dealerHand while dealerHand points < 17.

      

onDealClick looks like this:

onDealClick = event => {
  this.state.g.deal();
  this.setState({ g: this.state.g });
};

      

I know the recommended approach is to not mutate the state. But the truth is, it works great. And I have used this circuit many times. And everything seems to be working fine. As far as I can tell, these are the only drawbacks:

  • If I needed to do a dirty check on the mustComponentUpdate file (I don't), I would have to use deepEquals instead of comparing pointers.
  • If I need to undo (I don't) it will be more difficult to implement.
  • Moving to Redux can be painful as Redux will force me to use functional, immutable style rather than OO style.

Question: Are there other disadvantages that I am missing?

+3


source to share


1 answer


When called setState

to update the state, the component automatically calls shouldComponentUpdate

and reerenders as needed.

If you mutate the state directly, this change won't be automatically reflected in the UI until you render in some way. This bypasses React's state management by implementing your own state management.



React is simple and very flexible, so your path will work. However, I cannot recommend it.

0


source







All Articles