Blog>
Snippets

Optimizing Component Re-renders

Explain how to use TanStack Store selectors to selectively update components and reduce unnecessary re-renders for performance optimization.
import { useStore } from 'tanstack-store-react';

const selectBearsCount = state => state.bears.length;

export function BearsComponent() {
  // Only subscribe to the number of bears in the store
  const bearsCount = useStore(selectBearsCount);

  return <h1>{bearsCount} Bears</h1>;
}
This code demonstrates how to use a selector with TanStack Store to subscribe a component only to a specific piece of the state (in this case, the count of bears). This ensures the component only re-renders when the number of bears changes, rather than on any state change, optimizing performance.
import { useStore } from 'tanstack-store-react';

const selectBearNames = state => state.bears.map(bear => bear.name);

export function BearNamesComponent() {
  // Subscribe only to the names of the bears
  const bearNames = useStore(selectBearNames);

  return (<ul>{bearNames.map(name => <li key={name}>{name}</li>)}</ul>);
}
Here, a selector is used to create a list that subscribes only to the names of the bears. Since it specifically targets bear names, this component will only update when bear names change, minimizing unnecessary re-renders and improving UI performance.