Blog>
Snippets

Debugging State Changes in TanStack Store

Demonstrate a method for logging state changes in a TanStack Store, using a debug function that listens to state updates and logs them to the console, helping developers trace how and when their state changes.
import { createStore } from 'tanstack-store-react';
Import createStore from tanstack-store-react to create a new store.
const debugStateChanges = store => {
  store.subscribe((mutation) => {
    console.debug('State changed:', mutation);
  });
};
Define a debug function that subscribes to state changes in the store. It logs each mutation that occurs in the state.
const initialState = { counter: 0 };
const store = createStore({
  initialState
});
debugStateChanges(store);
Create an initial state and a store using tanstack-store-react. Then apply the debugStateChanges function to log any state mutations.