Blog>
Snippets

Using TypeScript with TanStack Store for Type-Safe State Management

Provide an example of creating a TanStack Store with TypeScript, focusing on defining types for the state, actions, and hooks to ensure type safety throughout the application's state management logic.
import { createStore } from '@tanstack/react-store';

interface CounterState {
  count: number;
}

interface CounterActions {
  increment: () => void;
  decrement: () => void;
}

const store = createStore<CounterState, CounterActions>({  
  initialState: { count: 0 },
  actions: (store) => ({
    increment: () => store.setState({ count: store.getState().count + 1 }),
    decrement: () => store.setState({ count: store.getState().count - 1 })
  })
});
This code sets up a TanStack Store with TypeScript by defining types for the store's state and actions. The `CounterState` type defines the structure of the store's state, which in this case contains a single property `count`. The `CounterActions` type defines the actions available for manipulating the state, with `increment` and `decrement` functions. The `createStore` function is used to create the store, specifying the initial state and actions.
import { useStore } from '@tanstack/react-store';

function useCounter() {
  const [state, actions] = useStore(store);
  return { ...state, ...actions };
}
This code demonstrates creating a custom hook, `useCounter`, utilizing the TanStack Store created previously. The hook uses the `useStore` function to access the store's state and actions. It then spreads and returns both the state and actions together, allowing components to easily access and manipulate the counter state.