Blog>
Snippets

State Immutability Practices in TanStack Store

Explain the importance of maintaining state immutability in TanStack Store through examples, highlighting best practices to ensure state integrity during updates.
import { createStore } from '@tanstack/store';

const initialState = { count: 0 };

const store = createStore({
  initialState,
  onUpdateState: (state) => ({ ...state }),
});
This code snippet demonstrates the creation of a simple store using TanStack Store with initialState containing a count property. The onUpdateState callback is utilized to ensure state immutability by creating a new state object using object spread syntax, thereby maintaining state integrity.
store.updateState(currentState => ({ ...currentState, count: currentState.count + 1 }));

store.updateState(currentState => ({ ...currentState, count: currentState.count - 1 }));
Here, two updateState calls are made to increment and decrement the count property of the store's state, respectively. Each update operation spreads the current state into a new object and then updates the count property, ensuring the state remains immutable during updates.
const incrementCount = () => {
  store.updateState(state => ({ ...state, count: state.count + 1 }));
};

const decrementCount = () => {
  store.updateState(state => ({ ...state, count: state.count - 1 }));
};
These functions, incrementCount and decrementCount, encapsulate the logic for updating the state's count property. By using functions to manage state updates, reusability and readability are enhanced, and the spread operator ensures that state mutations preserve immutability.