Blog>
Snippets

Using TanStack Store for Global State Management

Demonstrate how to use TanStack Store for managing global application state, including the creation of custom hooks for shared state logic.
import { createStore, createHook } from 'tanstack-store-react';

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

// Create a store
const store = createStore({
  initialState
});
This code initializes the TanStack Store with an initial state containing a `counter` property. It demonstrates the basic setup needed to create a global state management solution using TanStack Store.
const useCounter = createHook(store, {
  selector: state => state.counter,
  actions: {
    increment: () => state => ({ counter: state.counter + 1 }),
    decrement: () => state => ({ counter: state.counter - 1 })
  }
});
This code snippet creates a custom hook `useCounter` using TanStack Store's `createHook` function. The hook focuses on the `counter` state and provides `increment` and `decrement` actions to modify it. It showcases how to encapsulate and share state logic across components.
import React from 'react';

function CounterComponent() {
  const [counter, actions] = useCounter();

  return (
    <div>
      <p>{counter}</p>
      <button onClick={actions.increment}>Increment</button>
      <button onClick={actions.decrement}>Decrement</button>
    </div>
  );
}
This React component utilizes the `useCounter` hook created earlier to display and control the counter's state. It demonstrates how components can interact with the global state through actions defined in custom hooks, showcasing the practical implementation of the TanStack Store for state management.