Blog>
Snippets

Implementing Selectors with TanStack Store

Show how to create and use selectors with TanStack Store for deriving computed states, improving performance by avoiding unnecessary re-renders.
import { createStore } from '@tanstack/react-store';

const initialState = {
  users: [
    { id: 1, firstName: 'John', lastName: 'Doe'},
    { id: 2, firstName: 'Jane', lastName: 'Doe'}
  ]
};

const store = createStore({
  initialState
});
Creates a store with an initial state containing a list of users.
const selectUserFullName = state => state.users.map(user => `${user.firstName} ${user.lastName}`);

const fullNames = store.useState(selectUserFullName);
Defines a selector to derive full names from the users' first and last names. It then uses this selector to get the computed full names.