Redux Bad Practices #1: Lists as Arrays

Let’s say you need to save a list of items in the store.

One approach would be to save the data as an array on the store:

[
{ id: 1, name: 'Kate' },
{ id: 2, name: 'Jane' }
]

This will require you to iterate over the entire array to find an item, and will also make your reducers messier because handling arrays with immutable data is clumsy.

It is better to save the data as an object with unique IDs as keys. It will allow for easy access and also increase code readability and performance:

{
1: { id: 1, name: 'Kate' },
2: { id: 2, name: 'Jane' }
}

Also, don’t be tempted to remove the id property from the values. When a component selects a single item from the state it has no access to the key but might need to know the id of the item:

UserCard = (user) => {
if (currentUserId === user.id) { }
...
}
connect((state, props) => ({
user: state.users[props.id],
currentUserId: state.currentUser.id
})(UserCard);

Only store lists in the state as arrays if the only thing you need is iterating over them. When it comes to accessing or updating specific values, using objects would be much easier and efficient.



Originally published at 500tech.com.