Redux Bad Practices: Lists as Arrays
Adam Klein
Last updated on Dec 5, 2017

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

A bad 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) {
    // don't remove the ID property from the user
  }

  ...
}

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

Only store lists in 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.

Back to all articles

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