Redux Bad Practices: Nested State
Adam Klein
Last updated on Nov 17, 2017

Complex applications usually deal with data structures that have associations, e.g. posts that have comments.

A bad approach would be to save the data nested in the state:

posts:
  id: 1
  title: 'Better Redux'
  comments:
    id: 2
    text: 'Great article!'

A good 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 of 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 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.

Back to all articles

© 500Tech. Building high-quality software since 2012.