Using Selectors for Derived States
Illustrate the use of selectors in TanStack Store to compute derived states from the base state, enhancing reusability and minimising unnecessary recalculations.
const store = createStore({
initialState: {
items: [
{ name: 'Apples', quantity: 2, pricePerItem: 1.5 },
{ name: 'Oranges', quantity: 4, pricePerItem: 0.75 }
]
},
selectors: {
totalPrice: (state) => state.items.reduce((total, item) => total + item.quantity * item.pricePerItem, 0)
}
});
This code snippet initializes a store with an initial state containing a list of items, each with a name, quantity, and price per item. It then defines a selector 'totalPrice' to compute the total price of the items in the store. The selector uses the reduce method to calculate the total, ensuring that the computation is only redone when the items array changes, thanks to the memoization capabilities of selectors.
function ShoppingCartTotal() {
const totalPrice = useStoreState(store.selectors.totalPrice);
return (
<div>
Total Price: {totalPrice}
</div>
);
}
This React component 'ShoppingCartTotal' utilizes the 'useStoreState' hook to subscribe to the 'totalPrice' selector from the store. It renders the computed total price in a div. Whenever the items in the store change, leading to a change in the total price, this component will re-render with the updated value, demonstrating efficient state subscription and rendering.