Blog>
Snippets

Utilizing Router Context for Global State Management

Explain how to leverage TanStack Router's context feature to manage global application state, demonstrating passing and retrieving state across components without prop drilling.
import { createBrowserRouter, RouterProvider, createRoutesFromElements, Route } from 'tanstack-router-react';
import React, { createContext, useContext, useState } from 'react';

const GlobalStateContext = createContext();
This code imports necessary modules from TanStack Router and React. It then creates a context object for the global state using React's createContext.
function GlobalStateProvider({ children }) {
  const [globalState, setGlobalState] = useState({});
  return (
    <GlobalStateContext.Provider value={{ globalState, setGlobalState }}>
      {children}
    </GlobalStateContext.Provider>
  );
}
Defines a GlobalStateProvider component that will wrap the application's component tree, allowing any child components to access and modify the global state.
function useGlobalState() {
  const context = useContext(GlobalStateContext);
  if (context === undefined) {
    throw new Error('useGlobalState must be used within a GlobalStateProvider');
  }
  return context;
}
Creates a custom hook, useGlobalState, to provide a simple and cohesive way to access the global state context from any component, ensuring that it is used within the correct context provider.
const router = createBrowserRouter( createRoutesFromElements(
  <Route path="/" element={<GlobalStateProvider><App /></GlobalStateProvider>} />
));
Initializes the TanStack Router with a base route. The application component (App) is wrapped inside the GlobalStateProvider to provide global state management across the entire application.
function App() {
  const { globalState, setGlobalState } = useGlobalState();

  // Example usage
  const handleClick = () => {
    setGlobalState(prevState => ({ ...prevState, counter: (prevState.counter || 0) + 1 }));
  };

  return (
    <div>
      <h1>Global Counter: {globalState.counter}</h1>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}
Defines the main App component which utilizes the useGlobalState hook to access and update the global state. It includes an example of modifying the global state (a counter) and rendering its value.
function Root() {
  return <RouterProvider router={router} />;
}
Sets up the Root component that renders the RouterProvider from TanStack Router, passing the configured router as a prop to manage the routes for the application.