Blog>
Snippets

Creating Custom Hooks for State Management with TanStack Store

Demonstrate the creation of a custom React hook utilizing TanStack Store for managing and accessing application state in a more modular and reusable way.
import { createGlobalState } from '@tanstack/react-store';

// Define your store's initial state
const initialState = {
  counter: 0
};

// Create a global store
export const useGlobalCounterStore = createGlobalState(initialState);
This code snippet demonstrates how to create a global state using TanStack Store. It starts by importing the `createGlobalState` function from '@tanstack/react-store'. Then, it defines an initial state for the store, which in this case is an object with a `counter` property set to 0. Finally, it creates and exports a global store named `useGlobalCounterStore` using the `createGlobalState` function, passing the `initialState` as its argument. This global store can now be accessed and manipulated across the entire application.
import { useGlobalCounterStore } from './pathToYourStore/useGlobalCounterStore';

export function useCounter() {
  const [state, setState] = useGlobalCounterStore();

  const increment = () => setState(prevState => ({ counter: prevState.counter + 1 }));
  const decrement = () => setState(prevState => ({ counter: prevState.counter - 1 }));

  return { counter: state.counter, increment, decrement };
}
This snippet showcases how to create a custom hook named `useCounter` that utilizes the previously created global store `useGlobalCounterStore` for managing and accessing the counter state in a more modular and reusable way. It starts by importing the `useGlobalCounterStore` hook. Within the `useCounter` hook, it uses the state and setState methods provided by `useGlobalCounterStore` to get and update the counter state. Additionally, two functions, `increment` and `decrement`, are defined for increasing and decreasing the counter value, respectively. The hook then returns these functionalities along with the current counter value, allowing them to be easily utilized within components.