3

For example,

constructor(props) {
  super(props);
  this.state = {
    interactions: {
      liked: [],
      saved: [],
      receivedLikeRecently: null
  }
}

I'm trying to wrap my head around immutability, so if I wanted to now update receivedLikeRecently to true, would I have to do:

this.setState({
  interactions: {
    receivedLikeRecently: true
  }
});

What about the other values? Do I need to include them as well?

According to the documentation setState does a shallow merge so I assume the other nested properties would not copy over right? Or am I misunderstanding?

Thanks

  • Possible duplicate of [this.setState isn't merging states as I would expect](http://stackoverflow.com/questions/18933985/this-setstate-isnt-merging-states-as-i-would-expect) – jakeehoffmann Mar 30 '17 at 21:29
  • 1
    thanks. dang ok. i was just trying to unddrstand but i guess it has been asked before. should i delete this then? – 568798ausdf 7fa6tuysihdfk Mar 30 '17 at 21:32

2 Answers2

2

You should keep your state flat in order to avoid deep merging, which must be done manually and can get pretty annoying, besides causing a performance hit if done frequently.

Component.setState uses a simple === to test if properties have changed, which will cause it to always update object-valued properties of the state object.

Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39
1

You are correct, the nested state updates require more elaborate merging.

There is a concept of state normalization, described for Redux, but applicable to React state as well. http://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

The thinking is, think of the state as of a relational data store to ease working with it.

Tomáš Hübelbauer
  • 9,179
  • 14
  • 63
  • 125
  • Thanks. So for redux as well I should keep it in mind? If I understand assign (or spread operator) correctly, then as long as I use either, I can return the new object with however deep changes, correct? I have not yet touched redux, sorry if sounds very stupid.. just going by what I read in the short time. – 568798ausdf 7fa6tuysihdfk Mar 30 '17 at 21:38
  • With the spread operator it is very simple and nice looking to return a shallow copy of your state. For nested states libraries like Normalizr are helpful, but don't rush, solve your React proper before moving onto Redux. – Tomáš Hübelbauer Mar 30 '17 at 21:39