Blog>
Snippets

Managing Global State with TanStack Store

Illustrate managing and accessing global state across different components in a React application using TanStack Store, emphasizing patterns for sharing state.
import { createStandaloneStore } from '@tanstack/store-react';

// Define our global state shape
const store = createStandaloneStore({
  state: () => ({
    counter: 0
  }),
  actions: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    }
  }
});
First, we import the necessary functionalities from TanStack Store and create a standalone store. The store contains a simple state with a counter and two actions to increment and decrement the counter.
export function CounterDisplay() {
  const counter = store.useState(state => state.counter);
  return (
    <div>
      <p>Current Count: {counter}</p>
    </div>
  );
}
This component consumes the 'counter' state from our global store. It uses the 'useState' hook provided by TanStack Store to access the current state of the counter.
export function CounterControls() {
  return (
    <div>
      <button onClick={() => store.actions.increment()}>Increment</button>
      <button onClick={() => store.actions.decrement()}>Decrement</button>
    </div>
  );
}
This component renders two buttons for incrementing and decrementing the global counter state. It utilizes the actions defined in our store to mutate the global state.