Blog>
Snippets

Creating a Custom Hook for State Management

Showcase the creation of a custom React hook that utilizes TanStack Store for managing and accessing application state within functional components.
import { useStore, createStore } from '@tanstack/react-store';

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

// Creating a store with initial state
export const counterStore = createStore(initialState);
This snippet creates a store using TanStack Store with an initial state. The store is centered around a 'counter' state.
export function useCounterStore() {
  // Accessing the store and its actions
  const [state, actions] = useStore(counterStore);

  // Increment action
  const increment = () => actions.set(draft => { draft.counter += 1; });

  // Decrement action
  const decrement = () => actions.set(draft => { draft.counter -= 1; });

  // Reset action
  const reset = () => actions.set(draft => { draft.counter = 0; });

  // Returning state and action handlers
  return { ...state, increment, decrement, reset };
}
This snippet defines a custom hook `useCounterStore` that uses the store created previously. It includes actions to increment, decrement, and reset the counter.