Blog>
Snippets

Creating Selective Subscriptions to State Changes

Showcase how to use selectors in TanStack Store for subscribing components to specific parts of the state only, to optimize rendering.
import { useState } from 'react';
import { useStore } from '@tanstack/react-store';
Import necessary hooks from React and useStore from TanStack Store.
const selectTodoById = (state, todoId) => state.todos.find(todo => todo.id === todoId);
Define a selector function to pick out a todo item by its ID from the global state.
function TodoComponent({ todoId }) {
  const todo = useStore(state => selectTodoById(state, todoId));
  return <div>{todo ? todo.title : 'Todo not found'}</div>;
}
A functional component that uses the useStore hook with a selector to subscribe to changes of a specific todo item identified by todoId.
function TodosCount() {
  const todosCount = useStore(state => state.todos.length);
  return <div>Todo count: {todosCount}</div>;
}
A functional component that subscribes to the length of the todos array in the state, re-rendering only when the count changes.