Blog>
Snippets

Modularizing State Management with TanStack Store

Exhibit how to modularize your state management by creating multiple stores for different application features and then combining them.
import { createStore } from '@tanstack/store-react';

// Define a store for user information
const userStore = createStore({
  initialState: {
    name: '',
    email: '',
  },
});
This code creates a store specifically for managing user information such as name and email. The 'createStore' function from '@tanstack/store-react' is used to define the initial state of the store.
import { createStore } from '@tanstack/store-react';

// Define a store for product information
const productStore = createStore({
  initialState: {
    products: [],
    category: '',
  },
});
Here, another store is created for managing product information, including a list of products and their selected category. This shows how separate aspects of the application's state can be managed independently.
// Example of combining store values in a component
import { useStore } from '@tanstack/store-react';

function UserProfile() {
  const userState = useStore(userStore);
  const productState = useStore(productStore);

  return (
    <div>
      <h1>User: {userState.name}</h1>
      <p>Email: {userState.email}</p>
      <p>Selected Product Category: {productState.category}</p>
    </div>
  );
}
This example demonstrates how to use multiple stores within a single component. The 'useStore' hook is utilized to access the state of both the 'userStore' and the 'productStore', showcasing how modular state management facilitates components that rely on multiple state sources.