Blog>
Snippets

Creating a Basic Store with TanStack Store

Demonstrate initializing a simple store with TanStack Store for maintaining and updating application state.
import { createStore } from '@tanstack/store-core';
Imports the createStore function from the @tanstack/store-core package.
const initialState = { counter: 0 };
Defines the initial state of the store with a counter set to 0.
const store = createStore({
  initialState,
  actions: {
    increment(state) {
      state.counter += 1;
    },
    decrement(state) {
      state.counter -= 1;
    }
  }
});
Creates a new store instance with the initial state and actions. Actions include increment and decrement functions to modify the state.
store.subscribe((state) => {
  console.log('New state:', state);
});
Subscribes to state changes and logs the new state to the console whenever it is updated.
store.dispatch('increment');
Dispatches the 'increment' action to update the state by increasing the counter.