Blog>
Snippets

Optimizing React Component Rerenders with TanStack Store

Provide an example of how to utilize TanStack Store's capabilities to minimize unnecessary React component rerenders, focusing on leveraging the library's built-in efficiency.
import { createStore, useStore } from '@tanstack/react-store';

// Define your store with an initial state
cconst myStore = createStore({ counter: 0 });
Creates a store with an initial state. The 'counter' is set to 0 as the initial state.
function incrementCounter() {
  myStore.setState(prevState => ({
    counter: prevState.counter + 1
  }));
}
Defines a function to increment the 'counter' state within the store. The 'setState' method is used to update state based on the previous state.
function CounterComponent() {
  const counter = useStore(myStore, state => state.counter);

  return (
    <div>
      <p>Counter: {counter}</p>
      <button onClick={incrementCounter}>Increment</button>
    </div>
  );
}
A functional React component that uses the 'useStore' hook to consume the 'counter' state from 'myStore'. It only re-renders when the 'counter' state changes, thanks to the selector passed to 'useStore', thus minimizing unnecessary re-renders.