Blog>
Snippets

Optimizing UI Responsiveness with TanStack Router

Illustrate techniques for real-time UI updates in response to search parameter changes using TanStack Router, highlighting efficient state management to enhance user experience.
import { useSearchParam } from 'tanstack-react-router';

function FilterComponent() {
  // Using TanStack Router's hook to read a search param.
  const category = useSearchParam('category');

  // Logic to handle changes in category search param
  useEffect(() => {
    if (category) {
      // Fetch data or update UI based on the new category value
      console.log(`Category changed to: ${category}`);
      // FetchDataOrUpdateTimeConsumingTask(category);
    }
  }, [category]);

  return <div>Filter by category: {category}</div>;
}
This snippet demonstrates how to read a search parameter (`category`) using TanStack Router's `useSearchParam` hook and update the UI or fetch data whenever it changes. The `useEffect` hook is utilized for re-fetching data or updating the UI based on the category's new value. This provides real-time UI updates in response to search parameter changes, optimizing user experience.
import { useNavigate } from 'tanstack-react-router';

function UpdateCategoryButton({ newCategory }) {
  // Hook to programatically navigate and change URL search params
  const navigate = useNavigate();

  const updateCategory = () => {
    // Updating the search param 'category' to a new value
    navigate({
      search: (search) => ({ ...search, category: newCategory }),
    });
  };

  return <button onClick={updateCategory}>Change Category to {newCategory}</button>;
}
This code showcases how to programmatically update a search parameter (`category`) to a new value using TanStack Router's `useNavigate` hook. Upon clicking the button, the `updateCategory` function is called, which updates the search parameter in the URL. This enables efficient state management and dynamic navigation, directly reflecting user interactions in the UI without full page reloads, thus enhancing the overall responsiveness and user experience.