Blog>
Snippets

Implementing Selectors for Computed State

Illustrate the use of selectors in TanStack Store for deriving computed state from the base state, and how to use this computed state within a React component.
import { createStore, useStore } from '@tanstack/react-store';

// Define the store and initial state
const store = createStore({
  todos: [
    { id: 1, text: 'Learn React', done: true },
    { id: 2, text: 'Learn TanStack Query', done: false }
  ]
});
This code snippet creates a store using TanStack Store with an initial state that includes a list of todos.
const selectDoneTodosCount = (state) => state.todos.filter(todo => todo.done).length;
This selector function computes the count of todos that are marked as done by filtering the 'todos' array from the store's state.
function DoneTodosCountComponent() {
  // Use the store and selector
  const doneTodosCount = useStore(store, selectDoneTodosCount);

  return <div>Done todos: {doneTodosCount}</div>;
}
This React component demonstrates the use of the 'useStore' hook to access the computed state (done todos count) in the UI.