Blog>
Snippets

Optimizing Re-renders with TanStack Store

Explain how to use TanStack Store’s capabilities to minimize unnecessary re-renders in Next.js applications, including code snippets that highlight best practices for efficient state updates.
import { createStore } from '@tanstack/react-store';

// Define the initial state
const initialState = {
  counter: 0
};

// Create a store with the initial state
export const store = createStore({
  initialState
});
This snippet initializes the TanStack Store with an initial state. A simple counter state is used for demonstration.
import { useStoreState } from '@tanstack/react-store';

export function CounterComponent() {
  // Subscribe only to the counter state
  const counter = useStoreState(store, (state) => state.counter);

  return <div>{counter}</div>;
}
This snippet demonstrates how to subscribe to a specific part of the state (the counter value) within a React component using the `useStoreState` hook. This ensures the component only re-renders when the counter state changes.
store.setState((state) => {
  // Increment the counter state
  state.counter += 1;
});
This code updates the counter state by incrementing its value. Updating the state in this manner ensures that only components subscribed to the counter state will re-render, optimizing the application's performance.