Blog>
Snippets

Synchronizing State with URL Parameters

Demonstrate bidirectional synchronization between a React component's state and URL query parameters using TanStack Config.
import { useSearchParams } from 'tanstack/react-location';

function SearchPage() {
  let [searchParams, setSearchParams] = useSearchParams();

  const handleChange = (e) => {
    // Update the state and sync with URL
    setSearchParams({ search: e.target.value });
  };

  return (
    <input
      value={searchParams.search || ''}
      onChange={handleChange}
      placeholder='Search...'
    />
  );
}
This snippet demonstrates setting up a search input that synchronizes its state with the URL's query parameters using TanStack's useSearchParams hook from React Location. When the input changes, it updates the URL without a page reload.
import { useEffect } from 'react';
import { useSearchParams } from 'tanstack/react-location';

function Filters() {
  let [searchParams, setSearchParams] = useSearchParams();
  useEffect(() => {
    // Sync URL with state when component mounts
    const filters = searchParams.filters ? JSON.parse(searchParams.filters) : {};
    // Assume setFilters is a state setter for your filter
    setFilters(filters);
  }, []);

  const handleFilterChange = (newFilters) => {
    // Update filters in state and URL
    setSearchParams({ filters: JSON.stringify(newFilters) });
  };

  // Your filter UI here
}
This example demonstrates how to read from URL parameters to set the state when the component mounts, and how to update URL parameters when the filters change. It uses useEffect to read the initial state from the URL and applies it to the component's state.