Redux Bad Practices #3: Nested State

Adam Klein
1 min readFeb 27, 2019

--

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.

Originally published at 500tech.com.

--

--