Blog>
Snippets

Optimizing Component Re-renders with TanStack Store Selectors

Demonstrate the use of selectors in TanStack Store to compute derived data, reducing unnecessary component re-renders.
import { createStore, createSelector } from '@tanstack/react-store';
First, we import createStore and createSelector from the TanStack Store package.
const store = createStore({
  initialState: {
    todos: [
      { id: 1, title: 'Learn TanStack Store', completed: false },
      { id: 2, title: 'Build an app', completed: true }
    ]
  }
});
Then, we create a store with an initial state that includes a todos array.
const selectTodos = state => state.todos;
Define a simple selector for extracting todos directly from the state.
const selectCompletedTodos = createSelector(
  selectTodos,
  todos => todos.filter(todo => todo.completed)
);
Use createSelector to derive completed todos. This creates a memoized selector that only recalculates when todos change.
const App = () => {
  const completedTodos = store.useStore(selectCompletedTodos);

  return (
    <div>
      <h1>Completed Todos</h1>
      <ul>
        {completedTodos.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </div>
  );
};
Finally, create a React component that uses the store and our selector. It only re-renders when completed todos change, not when any todo changes.