Redux Bad Practices #4: Duplicate State
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.
All articles in this series:
https://medium.com/@adamklein_66511/redux-bad-practices-1-lists-as-arrays-9115ba87b0ce
https://medium.com/@adamklein_66511/redux-bad-practices-2-duplicate-code-9f2f3d774d4d
https://medium.com/@adamklein_66511/redux-bad-practices-3-nested-state-6eebf1a410df
https://medium.com/@adamklein_66511/redux-bad-practices-5-duplicate-state-996d259758e3
https://medium.com/@adamklein_66511/redux-bad-practices-6-new-objects-on-the-fly-c38b503948a5
https://medium.com/@adamklein_66511/redux-bad-practices-7-mix-ui-state-with-model-data-cdca6c8d8fd9
Originally published at 500tech.com.