Redux Bad Practices: Duplicate State

Adam Klein

Let’s say you need to display a filtered list of products.

bad approach would be to save the filtered list on each filter change in a component’s state or in a different key in a Redux store.

onFilterChange(filter) {
  this.setState({
    filteredProducts: this.props.products.filter(...)
  })
}

good approach would be to use cached selectors with reselect:

mapStateToProps = (state) => ({
  filteredProducts: filteredProductsSelector(state)
})

Or calculate the computed data on render if it’s not shared and runs fast:

render() {
  const filteredProducts = this.props.products.filter(...);

  return <div>{ filteredProducts.map(...) }</div>;
}

Redux offers you a mechanism for a single source of truth. If you save different representations of the same data in your store or in component’s state you are violating that principal. You should only save raw data once, and calculate everything that can be derived from it.

Popular