Redux Bad Practices #3: Nested State
Complex applications usually deal with data structures that have associations, e.g. posts that have comments.
You might save the data nested in the state:
posts:
id: 1
title: 'Better Redux'
comments:
id: 2
text: 'Great article!'
But a better approach would be to flatten the state and operate with foreign IDs on the data.
posts:
id: 1
title: 'Better Redux'
comments:
id: 2
postId: 1
text: 'Great article!'
There are multiple disadvantages to storing a nested state.
Nested data structures are harder to maintain and explore. Nesting doesn’t allow for sharing associated models (many to many), for example, comments can be on posts, and on images.
It’s easier to gain good performance with a flat state because the optimization works on comparing references. Changing a nested comment will force the change of the entire post object.
It’s also harder to find a nested object by ID; you’ll need to pass around the full path to the object.
And last but not least, it’s easier to debug the state when it’s fairly flat.
All articles in this series:
https://medium.com/@adamklein_66511/redux-bad-practices-1-lists-as-arrays-9115ba87b0ce
https://medium.com/@adamklein_66511/redux-bad-practices-2-duplicate-code-9f2f3d774d4d
https://medium.com/@adamklein_66511/redux-bad-practices-3-nested-state-6eebf1a410df
https://medium.com/@adamklein_66511/redux-bad-practices-5-duplicate-state-996d259758e3
https://medium.com/@adamklein_66511/redux-bad-practices-6-new-objects-on-the-fly-c38b503948a5
https://medium.com/@adamklein_66511/redux-bad-practices-7-mix-ui-state-with-model-data-cdca6c8d8fd9
Originally published at 500tech.com.