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.
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.