Blog>
Snippets

Deferred API Calls on Route Change

Demonstrate deferring API calls until a route is activated with TanStack Router, optimizing network usage and enhancing user experience.
import { useNavigate } from 'tanstack-router-dom';

function MyComponent() {
  // Defining navigate for route navigation
  let navigate = useNavigate();

  // Function to navigate and fetch data
  function navigateAndFetchData(to) {
    navigate(to, {
      // This callback only triggers when the navigation is confirmed
      state: { fetchDataOnMount: true }
    });
  }

  return (
    <button onClick={() => navigateAndFetchData('/new-route')}>Go to New Route</button>
  );
}
This code snippet demonstrates how to navigate to a new route while indicating that data should be fetched only after the route has been activated. It utilizes the `useNavigate` hook from TanStack Router to perform navigation and pass state information indicating that API calls should be deferred until the component mounted on the new route.
import { useEffect } from 'react';
import { useLocation } from 'tanstack-router-dom';

function DataFetcherComponent() {
  const { state } = useLocation();

  useEffect(() => {
    // Check if navigation state requests data fetching
    if (state?.fetchDataOnMount) {
      fetchData();
    }
  }, [state]);

  function fetchData() {
    // Function to fetch data from an API
    console.log('Fetching data for the route...');
    // API call logic goes here
  }

  return (
    <div>Loading new content...</div>
  );
}
This code snippet demonstrates how to react to navigation with deferred data fetching in the component mounted on the new route. Leveraging the `useLocation` hook to access the navigation state, it conditionally triggers data fetching within a `useEffect` hook, based on the presence of a custom state parameter (`fetchDataOnMount`), indicating that the component should fetch data once it has been mounted.