17

I'm using ReactJs with Redux and on some tutorials and codes I see people suggesting and using normalizr to keep the state flat. But what is the real advantage in keeping it flat ? Will I encounter any problems if I don't ? Is it necessary ?

2 Answers 2

32

Three main reasons:

  • Updating nested Javascript objects immutably generally results in uglier code that is harder to maintain, unless you use a utility library to wrap up the process
  • Immutably updating nested data requires that you return new copies of all items in the nesting hierarchy. Since components generally do shallow-equality reference comparisons on data to see if they need to update, updating nested data usually means that more objects are updated, and more components will probably have to re-render even if the actual data isn't different.
  • Flat data, and in particular normalized data, enables some more optimized approaches for defining components (such as a list where each list item component is itself connected, given an item ID as a prop, and is responsible for looking up its own item's data by that ID)
1
  • 1
    thanks a lot for your great answer. it totally convinced me and helped me understand it better :) Aug 9, 2016 at 17:22
10

I'm assuming that by keeping it flat, you mean not having nesting in your state object.
It is not advisable to have nesting in your state because you have to keep changing your state according to some events.
If you look at redux documentation, they want you to have pure reducers. And part of making your function pure is not modifying it's arguments.
When you have lots of nesting it's difficult to change state without inadvertently modifying the state object because all JS objects are passed by reference. When you have a lot of nesting you have to make deep copies of the state object before modifying it.

1
  • 1
    Thanks a lot ! now I can't imagine not flattening my states :) Aug 9, 2016 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.