Why should I keep the state flat

I use ReactJs with Redux and on some tutorials and codes that I see people suggesting and using normalizr to keep the state flat . But what is the real advantage of keeping it flat? Will I have problems if I don’t? It's necessary?

+6
source share
2 answers

Three main reasons:

  • Updating Javascript nested objects invariably tends to result in ugly code that is harder to maintain if you don't use the utility library to complete the process
  • Constantly updating nested data, you need to return new copies of all elements of the nesting hierarchy. Because components usually perform incomplete comparisons for data to check if they need to be updated, updating nested data usually means more objects are being updated and more components may have to be re-displayed, even if the actual data is no different friend.
  • Flat data, and in particular normalized data, allows you to use some more optimized approaches for defining components (for example, a list in which each component of a list item is itself connected, taking into account the identifier of the element as a support and is responsible for finding its own data for the element by this identifier)
+6
source

I assume that by keeping it flat you mean not having nesting in your state object.
It is not recommended to have nesting in your state, because you need to constantly change state in accordance with some events.
If you look at the reduction documentation, they want you to have clean gearboxes. And part of making your function clean does not change its arguments.
When you have a lot of nesting, it is difficult to change state without inadvertently changing the state object, because all JS objects are passed by reference. When you have a lot of nesting, you must make deep copies of the state object before modifying it.

+6
source

All Articles