Blog>
Snippets

Using Selectors for Computed States in TanStack Store

Illustrate the use of selectors in TanStack Store to compute derived state, showing how to efficiently calculate and memoize results based on the store's state.
import { createStore, createSelector } from '@tanstack/store-react';

// Initial state
const initialState = {
  products: [
    { id: 1, name: 'Book', price: 9.99 },
    { id: 2, name: 'Pen', price: 1.99 },
    { id: 3, name: 'Pencil', price: 0.99 }
  ]
};

// Create store
const store = createStore({
  initialState
});
This block initializes the store with a list of products, each having an id, name, and price.
const selectProducts = state => state.products;

const selectTotalPrice = createSelector(selectProducts, (products) =>
  products.reduce((total, product) => total + product.price, 0)
);
Here we define two selectors: one for fetching the products directly from the state, and another to compute the total price of all products. The latter uses createSelector for memoization, ensuring the computation is only rerun when products change.
const totalPrice = selectTotalPrice(store.getState());
console.log(`Total Price: $${totalPrice}`);
This code retrieves and logs the total price of all products by using the previously defined selector. It demonstrates accessing computed states efficiently.