Blog>
Snippets

Optimizing React Component Renders with TanStack Store

Exhibit the use of TanStack Store's selectors to optimize the re-rendering of React components, comparing it with the context API misuse that leads to unnecessary renders.
import { createContext, useContext, useMemo } from 'react';
const DataContext = createContext();

function DataProvider({ children }) {
  const value = useMemo(() => ({
    data: 'Some data',
    otherValue: 'Another value'
  }), []);

  return <DataContext.Provider value={value}>{children}</DataContext.Provider>;
}

function ConsumerComponent() {
  const { data } = useContext(DataContext);
  console.log('ConsumerComponent re-rendered');
  return <div>{data}</div>;
}
This example demonstrates how using a context without a selector leads to unnecessary re-renders. Even if `otherValue` changes and `data` does not, `ConsumerComponent` will still re-render because it consumes the `DataContext`. This is inefficient, especially in complex applications.
import { createStore } from '@tanstack/store-react';
import { useStore } from '@tanstack/react-query';

const store = createStore({
  initialState: {
    data: 'Some data',
    otherValue: 'Another value'
  }
});

function OptimizedComponent() {
  const selectedData = store.useStore((state) => state.data);
  console.log('OptimizedComponent re-rendered');
  return <div>{selectedData}</div>;
}
This example showcases the use of TanStack Store's selectors to optimize re-renders. By using `store.useStore` with a selector that only targets the `data` part of the state, `OptimizedComponent` will only re-render when `data` changes. Changes to `otherValue` will not trigger a re-render, making this method more efficient than the previous context example.