Skip to content

Instantly share code, notes, and snippets.

@kubk
Last active November 6, 2020 10:10
Show Gist options
  • Save kubk/c64a8a7755ea090a7d775e000c91bbe5 to your computer and use it in GitHub Desktop.
Save kubk/c64a8a7755ea090a7d775e000c91bbe5 to your computer and use it in GitHub Desktop.
Mobx VS Reselect comparison
const store = makeAutoObservable({
shop: {
taxPercent: 8,
items: [
{ name: 'apple', value: 1.20 },
{ name: 'orange', value: 0.95 },
]
},
get subtotal() {
return this.shop.items.reduce((acc, item) => acc + item.value, 0);
},
get tax() {
return this.subtotal * (this.shop.taxPercent / 100)
},
get total() {
return { total: this.subtotal + this.tax }
}
})
console.log(store.subtotal) // 2.15
console.log(store.tax) // 0.172
console.log(store.total) // { total: 2.322 }
const shopItemsSelector = state => state.shop.items
const taxPercentSelector = state => state.shop.taxPercent
const subtotalSelector = createSelector(
shopItemsSelector,
items => items.reduce((acc, item) => acc + item.value, 0)
)
const taxSelector = createSelector(
subtotalSelector,
taxPercentSelector,
(subtotal, taxPercent) => subtotal * (taxPercent / 100)
)
export const totalSelector = createSelector(
subtotalSelector,
taxSelector,
(subtotal, tax) => ({ total: subtotal + tax })
)
let exampleState = {
shop: {
taxPercent: 8,
items: [
{ name: 'apple', value: 1.20 },
{ name: 'orange', value: 0.95 },
]
}
}
console.log(subtotalSelector(exampleState)) // 2.15
console.log(taxSelector(exampleState)) // 0.172
console.log(totalSelector(exampleState)) // { total: 2.322 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment