Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 50 ยท Params and Search Params

useLocation and Navigation State

Understand the location object: pathname, search, hash, key and navigation state. Learn to pass state with links and return users to the previous page.

Every time the URL changes, React Router builds a location object describing "where we are now", and useLocation() gives it to any component. You have already used pieces of it indirectly: useParams reads the pathname, useSearchParams reads the search. useLocation is the low-level view, and it has two fields that are not part of the visible URL at all: a unique key and an arbitrary state payload that travels with a navigation.

Those two fields solve a handful of everyday problems: sending a visitor "back to the results they came from" with the filters intact, showing a one-time "Saved" message after a redirect, and noticing that the user navigated to the same URL again. They also have sharp edges, because state is invisible, unshareable and not guaranteed to exist. This lesson shows how to use it safely.

The location object

A location has five fields:

JSX
import { useLocation } from "react-router";

function Debug() {
  const location = useLocation();
  // For the URL  https://example.com/products?page=2#reviews
  // location.pathname -> "/products"
  // location.search   -> "?page=2"
  // location.hash     -> "#reviews"
  // location.state    -> whatever was passed with the navigation (or null)
  // location.key      -> a unique id for this history entry ("default" for the first one)
  return <pre>{JSON.stringify(location, null, 2)}</pre>;
}
flowchart LR
  subgraph URL["In the address bar"]
    P["pathname<br/>/products"]
    S["search<br/>?page=2"]
    H["hash<br/>#reviews"]
  end
  subgraph ENTRY["Stored with the history entry"]
    K["key<br/>unique id"]
    ST["state<br/>any cloneable value"]
  end

Three fields come from the URL itself; key and state belong to the history entry.

Points worth knowing:

  • pathname, search and hash are plain strings. search and hash include their leading ? and #, and are empty strings when absent. Parse the search with useSearchParams, not by hand (see Search Params and useSearchParams).
  • The hash is the part after #. It is meant for in-page anchors (#reviews). The server never sees it. The router does not scroll to it for you in plain declarative mode; the data-router ScrollRestoration component handles that (see Scroll Restoration, Focus and Page Titles).
  • key is a short random string that identifies one entry in the history stack. The very first entry has the key "default". If a user visits the same URL twice by navigating, the two entries have different keys. That makes key the right dependency for "run this each time the user navigates", where pathname would miss repeat visits.
  • useLocation re-renders its component on every navigation, because the location object changes. Components that only need one piece (a param, a query value) should use the narrower hooks so they re-render for fewer reasons.

Passing state with a navigation

Both Link and navigate accept a state value, and the next page reads it from useLocation().state:

JSX
<Link to="/products/7" state={{ from: "/products?category=gear" }}>Desk lamp</Link>

navigate("/products/7", { state: { from: "/products?category=gear" } });

// on the destination page
const { state } = useLocation();
console.log(state?.from); // "/products?category=gear", or undefined

The browser stores the state inside the history entry, using the same mechanism as history.state. That gives it unusual properties, which you must design around:

Situation Is state still there?
Back or forward to that entry Yes
Refreshing the page Usually yes (the entry survives a reload)
Opening the link in a new tab No
Typing or pasting the URL, or using a bookmark No
Sharing the link with someone No
Navigating to the same URL again without state No (a new entry with no state)

Two more rules follow from this:

  1. State must be cloneable. The browser copies it with the structured clone algorithm, so strings, numbers, plain objects and arrays are fine, but functions and DOM nodes are not, and class instances lose their prototypes. Keep it small and simple.
  2. State is a hint, never a requirement. Every page that reads state must work when it is null. State is for polish (a better "Back" target, a flash message), not for information the page cannot live without. If the page needs it, put it in the URL or load it from the server.

The stand-in router used in the demos keeps state in a Map keyed by URL instead of in the browser history, so it behaves like the real one for the cases in this lesson but does not survive a refresh. The real router persists state inside the browser's history entry.

See the location object change

The first demo prints every field of the location after each navigation, and keeps a list of the keys it has seen. Click the same link twice, then compare the "with state" and "without state" versions of the same address.

A location inspector

Click "with state": search and hash fill in, state shows {"from":"inspector"}, and a new key such as k1 joins the list. Click it a second time: the URL and state are unchanged, but a new key appears, because it is a new history entry. Now click "without state": the same address now has state of null. That is exactly what happens when someone opens the URL from a bookmark.

Returning to the page the user came from

The most common use of state is a better "Back" link. A product page can be reached from the full list, from a filtered list (/products?category=gear&page=3), or directly from a search engine. A fixed link to /products would drop the filters; navigate(-1) would work from the list but could send a visitor from a search engine back to the search engine.

The robust pattern: the list records where it is in the link's state, and the detail page uses that, with a fallback.

flowchart TD
  A["Detail page renders"] --> B{"location.state.from<br/>is a local path?"}
  B -- yes --> C["Back link goes to from<br/>(filters and page kept)"]
  B -- no --> D["Back link goes to /products<br/>(safe default)"]

State improves the Back link when it exists, and a fallback covers every other arrival.

JSX
function ProductRow({ product }) {
  const location = useLocation();
  return (
    <Link to={`/products/${product.id}`} state={{ from: location.pathname + location.search }}>
      {product.name}
    </Link>
  );
}

function BackLink() {
  const { state } = useLocation();
  const from = state?.from;
  const safe = typeof from === "string" && from.startsWith("/") && !from.startsWith("//");
  return <Link to={safe ? from : "/products"}>Back to results</Link>;
}

The safe check matters whenever you navigate to a value you did not just write yourself: only accept local paths, never full URLs. The same idea appears in the login redirect in Protected Routes and Auth Redirects.

The second demo implements it. The list has a category filter in the query string. Open a product from the filtered list, use the Back link, and notice the filter is still on. Then use "Open directly", which navigates without state like a bookmark would.

A Back link that remembers the filter

Start at "Products", choose "office", and open "Pen set". The page shows state of {"from":"/products?category=office"} and the Back link points at the filtered list. Press "Open directly (no state)": the state becomes null, the Back link falls back to /products, and the page still works. In this demo navigate is the stand-in function; in real React Router you would get it from useNavigate(), which is the next lesson's subject.

Flash messages and their gotcha

State is a handy way to show a message after a redirect:

JSX
// after saving
navigate("/orders/42", { replace: true, state: { flash: "Order saved" } });

// on /orders/42
const flash = useLocation().state?.flash;

Remember the table above: state survives a refresh. A visitor who reloads the page sees "Order saved" again. If that matters, clear the state once you have shown it, by replacing the entry with the same URL and no state: navigate(location.pathname + location.search, { replace: true }). For messages that must survive a full page load of a different kind (cookies, server sessions), use the server.

Other uses and when not to use state

  • Analytics and effects: run an effect on [location.key] to react to every navigation, including repeat visits to the same URL.
  • Modal background: keep the previous location in state so a modal can render over it (see Modal Routes and Background Locations).
  • Do not use state for data the page needs (put it in the URL or fetch it), for large objects, for anything sensitive that you would not store in the browser, or for anything that must be shareable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which useLocation() fields are NOT visible in the address bar?

    pathname, search and hash are parts of the URL. The key (a unique id for the history entry) and state (the payload passed with the navigation) are stored with the history entry.
  2. 2. A visitor opens a product page from a bookmark, and your Back link reads location.state?.from. What should happen?

    State exists only when the navigation carried it. Bookmarks, new tabs and shared links have none, so every page that reads state needs a fallback.
  3. 3. Which value can you safely put in navigation state?

    State is copied with the structured clone algorithm. Plain objects, arrays and primitives survive; functions and DOM nodes cannot be cloned, and class instances lose their methods.
  4. 4. Why is location.key useful as an effect dependency for page-view tracking?

    Each history entry gets its own key, so an effect keyed on it runs after every navigation, including repeat visits to the same pathname that a pathname dependency would skip.
  5. 5. A page shows state.flash after a redirect. The user refreshes. What do they most likely see?

    State lives in the history entry, which survives a reload. Clear it with a replace navigation after displaying the message if you want it to appear only once.

Summary

  • useLocation() returns pathname, search, hash, state and key; the component re-renders on every navigation.
  • key identifies a history entry and changes even when the URL repeats; state is a cloneable payload passed with a Link or navigate.
  • State survives Back, forward and usually a refresh, but not new tabs, bookmarks or shared links: always provide a fallback.
  • Use an explicit from in state, validated as a local path, for a Back link that keeps filters; navigate(-1) is simpler but can leave your site.
  • Clear flash-style state after showing it, and never rely on state for data the page needs.

Next: useNavigate and Imperative Navigation