Redux Bad Practices #6: Mix UI State with Model Data

In a Redux store, you may have both data from the server, together with the UI-related state. For example, you can have a list of products from the server, and save which one of those the user has selected using a checkbox.

One approach is to store the UI-related state and the data together:

{
products: {
1: { id: 1, name: 'Shirt', isSelected: true },
2: { id: 2, name: 'Pants' }
}
}

This example shows saving the isSelected attribute on the product object itself. In case you need to refresh the data from the server, you will override the user selection, or you'll need to perform a smart merge on the data to avoid losing it.

A better approach would be to always separate UI and model data:

{
products: {
1: { id: 1, name: 'Shirt' },
2: { id: 2, name: 'Pants' }
},
selectedProducts: { 1: true }
}

Saving the selection state outside the actual data will ensure you can always pull it from the server without worrying about overriding anything.



Originally published at 500tech.com.