Course contentsShow
← React
Lesson 1857 of 2,39643. RoutingFree lesson

Navigate with State: Passing Data Between Routes

Pass state objects through navigate() to share data without URL params or global state.

Navigate with State: Passing Data Between Routes

You'll learn how to pass data between routes without cluttering the URL or relying on global state.

When you navigate programmatically with useNavigate(), you can attach a state object that travels invisibly with the navigation. This is perfect for passing form data, selected items, or context that the destination route needs — without making your URLs messy or setting up complex state management.

How It Works

Think of route state like a sealed envelope you hand to someone while directing them to a new room. The URL is the room number everyone sees, but the envelope contains private information only the recipient can open.

The navigate() function accepts a second options argument where you specify state:

const navigate = useNavigate();

const goToDetails = () => {
  navigate('/product/123', {
    state: { 
      fromSearch: true,
      previousQuery: 'laptops' 
    }
  });
};

The destination route receives this data using useLocation():

import { useLocation } from 'react-router-dom';

function ProductDetails() {
  const location = useLocation();
  const { fromSearch, previousQuery } = location.state || {};

  return (
    <div>
      {fromSearch && <p>Back to "{previousQuery}" results</p>}
    </div>
  );
}

When to Use Route State

Route state is ideal for ephemeral data that enhances UX but isn't essential: showing a "back to search" button, pre-filling a form, or displaying a success message after navigation. Always provide fallback values (location.state || {}) because state disappears on page refresh.

Key Takeaway: Use the state option in navigate() to pass data invisibly between routes, keeping URLs clean while providing context to destination components — just remember it's not persisted across refreshes.