Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
11 replies
Roren

Reasons not to mutate React state

Hey everyone, this topic came up when I was chatting with a coworker who was less familiar with React, and I was hoping someone could shed some light on what is probably a very basic question.

If I have some piece of state, say for example const [person, setPerson] = useState({ name: 'Ed', age: 99 });, obviously if I were to mutate the object directly, it would not trigger any update and we'd be left with stale state.

However, if an update WERE to occur in lockstep with this mutation, would that have negative implications beyond simply not being a best practice? For example...

  const [person, setPerson] = useState({ name: 'Ed', age: 99 });
  const [_, forceUpdate] = useState();

  const change = () => {
    person.name = 'The Cooler Ed';
    forceUpdate();
  };

Obviously this is a contrived example, but you can see the point. The coworker in question is newer to React, and was mutating state but then another update was causing an update, so he hadn't realized it was an issue. I explained that this isn't good because it may introduce a bug if the code changes in the future, but I couldn't exactly describe whether or not there are any issues with changing prior state BEYOND this. Would it introduce issues? Or is it simply a matter of an update not occurring, which I've already described?
Was this page helpful?