Blog>
Snippets

Implementing Modular State Management with TanStack Store

Illustrate the concept of modular state management by splitting the application state into multiple stores using TanStack Store, including how to dynamically import and integrate these stores in a React app.
// userStore.js
export const useUserStore = createStore((set) => ({
  user: null,
  setUser: (user) => set({ user }),
}));
Defines a user store with initial state and an action to update the user data.
// themeStore.js
export const useThemeStore = createStore((set) => ({
  theme: 'light',
  toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })),
}));
Defines a theme store managing theme state with action to toggle between light and dark themes.
// App.js
import React, { Suspense } from 'react';
const UserComponent = React.lazy(() => import('./UserComponent'));
const ThemeComponent = React.lazy(() => import('./ThemeComponent'));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <UserComponent />
        <ThemeComponent />
      </Suspense>
    </div>
  );
}

export default App;
Lazily loads components related to the user and theme stores, demonstrating how to split and dynamically import parts of your app.
// UserComponent.js
import React from 'react';
import { useUserStore } from './userStore';

export default function UserComponent() {
  const { user, setUser } = useUserStore();
  // Event handler or effect to update user
  return <div>{user ? `Welcome ${user.name}` : 'Please log in'}</div>;
}
A component that uses the user store to display the user's information or a login prompt.
// ThemeComponent.js
import React from 'react';
import { useThemeStore } from './themeStore';

export default function ThemeComponent() {
  const { theme, toggleTheme } = useThemeStore();
  return (
    <button onClick={toggleTheme}>{`Switch to ${theme === 'light' ? 'dark' : 'light'} mode`}</button>
  );
}
A component that uses the theme store, displaying a button to toggle the app's theme.