Blog>
Snippets

Using Search Params for State Management in TanStack Router

Illustrate how to leverage URL search parameters for managing application state with TanStack Router, including reading and setting these parameters programmatically.
import { createBrowserRouter, RouterProvider, useSearchParams } from '@tanstack/react-router';

// Define a component that uses search params for state
function SearchParamsComponent() {
  let [searchParams, setSearchParams] = useSearchParams();
  return (
    <div>
      <h2>Current Search Param: {searchParams.get('filter')}</h2>
      <button onClick={() => setSearchParams({ filter: 'new-value' })}>Set Search Param to 'new-value'</button>
    </div>
  );
}
This code snippet demonstrates how to read and set search parameters in the URL using TanStack Router. This is useful for managing application state visible in the URL. The `useSearchParams` hook is used to access and manipulate the search parameters.
// Creating routes
const router = createBrowserRouter([
  {
    path: '/',
    element: <SearchParamsComponent />,
  },
]);

// In the App component
function App() {
  return <RouterProvider router={router} />;
}
This snippet sets up a basic router with TanStack Router and includes a route that renders the component defined previously. It shows how to integrate the component which manipulates search parameters into the routing system of a React application.