Why You Need to Normalize Redux Data
In my first Redux project, I made a huge mistake. I had data from an API that had deeply nested data. I simply added this data to a Redux store without normalizing the data. This lead to a lot of code bloat and performance issues. In this article, I’ll explore how to normalize data and the benefits it brings to React/Redux.
Un-normalized data
To make things concrete, let’s assume we create a component to render articles:
What if we want to change the information of a user?
If you simply mutate one of the posts, the component will not update with the user’s new information. You have to deep clone all the posts data or use immutable data structures. Even with ImmutableJS, changing deep structures can get messy:
Normalizing
We can pull out the author and each liker as a user
object into a map of all users. Then, replace each with a reference to the user
, instead of the object.
You could use a library such as normalizr to normalize data for you based on a schema. This is great if you have little control over your data, such as if you are using an external API.
We should also update the User component. We can pass it an id
that references a user and get the user object from Redux state:
Benefits
Now it is easy to update a user using this data. You can update the users without modifying any of the posts.
Because the posts do not change, the Post component does not need to update, only the User component does. In a similar fashion, reordering the likes only involves sorting the list of ids and does not cause each User component to update. This can lead to a huge performance win if you have a lot of likes.
Published 12 Dec 2017
Originally published at hgogonis.me.