Redux Bad Practices #4: Duplicate State

Adam Klein
1 min readFeb 27, 2019

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

One 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(...)
})
}

A better 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>;
}

Or use ‘useMemo’ hook to memoize it:

myComp({ products }) {
const filteredProducts = useMemo(
() => products.filter(...), [products]
);
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 principle. You should only save raw data once, and calculate everything that can be derived from it.

Originally published at 500tech.com.

--

--