Redux Bad Practices: Mix UI State with Model Data
Adam Klein
Last updated on Dec 5, 2017

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

A bad 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 good 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.

Back to all articles

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