Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 50 ยท Navigating Programmatically

useNavigate and Imperative Navigation

Use useNavigate to change pages from code: navigate(to), back and forward with deltas, replace, state, redirects after a form submit, and what to avoid.

Links are for navigation the user chooses. Sometimes, though, the program decides where to go next: a form was saved and you want to show the new record, a login succeeded, a "Back" button was pressed, a countdown reached zero. For those cases React Router gives you the useNavigate hook, which returns a function that changes the location from code.

The function is simple. The skill is knowing when to call it, which options to pass, and when a different tool (a Link, a <Navigate> element, or a loader redirect) is the better choice. This lesson also covers the most common mistake, calling navigate from an effect, and explains why it is risky. It builds on useLocation and Navigation State.

The basics

useNavigate() returns a function. Call it with a destination:

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

function CancelButton() {
  const navigate = useNavigate();
  return (
    <button type="button" onClick={() => navigate("/notes")}>
      Cancel
    </button>
  );
}

The destination can be an absolute path ("/notes"), a relative one ("..", "edit", resolved exactly like link targets: see Relative Links and Relative Routing), a path with a query string and hash ("/notes?sort=title#top"), or a path object ({ pathname: "/notes", search: "?sort=title" }).

The second argument holds options:

Option Meaning
replace: true Replace the current history entry instead of adding a new one
state: value Attach navigation state, read later with useLocation().state
relative: "path" Resolve .. against the URL path instead of the route tree
preventScrollReset: true Keep the scroll position (data and framework modes)
JSX
navigate("/notes/7", { replace: true, state: { created: true } });

Going back and forward with a number

Pass a number instead of a path and navigate moves through the history stack, just like the browser's Back and Forward buttons: navigate(-1) goes back one entry, navigate(1) forward one, navigate(-2) back two.

JSX
<button type="button" onClick={() => navigate(-1)}>Back</button>

There is a catch. A number does not mean "the previous page of my app". It means "the previous entry in the browser's session history", which could be a different website if the user arrived from a search engine, or nothing at all if this was the first page they opened. If there is no entry that far back, nothing happens (browsers ignore a jump that is out of range).

The location's key offers a cheap guard. The very first entry of a session has the key "default", so a different key means the user has navigated within the app at least once:

JSX
function BackButton({ fallback = "/" }) {
  const navigate = useNavigate();
  const location = useLocation();
  const canGoBack = location.key !== "default";
  return (
    <button type="button" onClick={() => (canGoBack ? navigate(-1) : navigate(fallback))}>
      Back
    </button>
  );
}

When you know exactly where the user should end up, prefer an explicit destination (or the from state pattern from the previous lesson). Deltas are for "undo my last step" behavior.

Push or replace

By default navigate(path) pushes a new entry on the history stack. With { replace: true } it overwrites the current entry. The difference decides what the Back button does afterwards. Think of a "create note" form that ends on the page of the new note:

flowchart LR
  subgraph PUSH["Push after saving"]
    P1["/notes"] --> P2["/notes/new"] --> P3["/notes/7 (current)"]
  end
  subgraph REPL["Replace after saving"]
    R1["/notes"] --> R2["/notes/7 (current)"]
  end

After a push, Back returns to the empty form. After a replace, Back skips it and returns to the list.

Use replace when the page you are leaving has no value in the history: a form that was just submitted, a login page after signing in, a redirect, an automatically corrected URL. Use a normal push when the user would think "I moved to a new page".

The classic use of navigate is the end of a submit handler. Do the work first, then move on, and replace the form's entry so Back does not show a filled-in form again:

JSX
function NewNote() {
  const navigate = useNavigate();

  async function handleSubmit(event) {
    event.preventDefault();
    const note = await saveNote(new FormData(event.currentTarget));
    navigate(`/notes/${note.id}`, { replace: true, state: { created: true } });
  }

  return <form onSubmit={handleSubmit}>{/* fields */}</form>;
}

Navigate only after the save succeeds. If it fails, stay on the form and show the error. In data mode a route action plus redirect() does the same job without a hook (see Actions and Form), and it is usually the better choice there. The hook remains the right tool for code that is not a form submission.

The first demo is a small notes app that does exactly this. Add a note, and notice that you land on the new note, with a "saved" banner that came from navigation state. Then open the note from the list again: no banner, because that navigation carried no state.

Save a note, then navigate to it

Open "New note", press Save with an empty title (you stay on the form with an error), then enter a title and save. In the real browser, the replace means the form's history entry is gone: Back would take you to the list, not to the form. As before, the navigate here is the stand-in function; in real code you get it from useNavigate().

See the history stack

History behavior is hard to picture, so the second demo uses a tiny in-memory history, the same idea as createMemoryRouter (used in tests and non-browser apps). The list shows every entry and which one is current. Try these sequences:

  1. Press "push /a", "push /b", "push /c": the stack grows to four entries.
  2. Press "navigate(-2)": the current marker moves back two entries and nothing is deleted.
  3. Press "push /c" again: the forward entries (the old /b and /c) are discarded, because pushing from the middle of the stack starts a new branch.
  4. Press "replace with /x": the current entry changes and the stack length stays the same.
  5. Press "navigate(-5)": the jump is out of range, so nothing happens.
Push, replace and go(delta) on a history stack

The same rules govern the browser's real history stack. The only difference is that the browser also lets users navigate to pages outside your app, which you cannot see or control.

Which tool for which job?

useNavigate is one of four ways to change the location. Pick the one that matches who triggers the change and when:

flowchart TD
  A["Need to change the page"] --> B{"Who decides?"}
  B -- "The user clicks" --> C["Link or NavLink"]
  B -- "Your code after an event<br/>(submit, timer, async result)" --> D["useNavigate"]
  B -- "A condition during render" --> E["Navigate element"]
  B -- "Before the page renders<br/>(data mode)" --> F["redirect() in a loader or action"]

Links for clicks, navigate for event-driven code, <Navigate> for render-time conditions, redirect() for data mode.

Avoid navigate inside effects

A very common pattern looks harmless:

JSX
// Avoid
function Dashboard({ user }) {
  const navigate = useNavigate();
  useEffect(() => {
    if (!user) {
      navigate("/login");
    }
  }, [user, navigate]);

  return <h1>Welcome, {user?.name}</h1>;
}

It has several problems. The component renders first and only redirects afterwards, so protected content can flash on screen (and the page is already in the DOM for a moment). In server rendering the effect never runs at all, so the server sends the page as if the user were logged in. In some router setups the navigate function changes identity when the location changes, so listing it as a dependency can re-run the effect. And a push (instead of replace) leaves a "dead" entry in history that bounces the user back to the page they just left.

Better options:

JSX
// 1. A render-time redirect: Navigate is a component that redirects for you
function Dashboard({ user }) {
  if (!user) {
    return <Navigate to="/login" replace />;
  }
  return <h1>Welcome, {user.name}</h1>;
}

// 2. In data mode, redirect before rendering anything
export async function loader({ request }) {
  const user = await getUser(request);
  if (!user) {
    throw redirect("/login");
  }
  return user;
}

navigate in an effect is acceptable when the effect truly responds to an event you cannot attach a handler to, such as "this subscription fired" or "this timer elapsed". If you can call navigate in an event handler, do that instead.

Do not use navigate for ordinary links. A <button onClick={() => navigate("/pricing")}> cannot be opened in a new tab, has no real URL for assistive technology and search engines, and ignores middle clicks. Use <Link to="/pricing">.

Code that is not a component (a fetch wrapper that sees a 401 response, say) cannot call hooks. With a data router created by createBrowserRouter, the router object has its own method: router.navigate("/login"). Keep one exported router instance and call it from anywhere. In declarative mode, pass the navigate function into the code that needs it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does navigate(-1) do?

    A number moves through the session history. It is not the parent route (that is ..) and not necessarily a page of your app: the previous entry could even be another website.
  2. 2. After saving a new note, you call navigate to the new note's URL with the option replace set to true, from the form page. What does the Back button do next?

    Replace overwrites the form's history entry with the note page, so the form is no longer in the stack. Back goes to whatever came before the form.
  3. 3. Why is useEffect(() => { if (!user) navigate("/login") }, [user]) a poor way to protect a page?

    Effects run after the first render, so the protected UI appears briefly, and on the server effects do not run. Prefer a <Navigate> element for render-time redirects or a loader redirect in data mode.
  4. 4. You pass navigate(-3) but the user has only one earlier entry in the history. What happens in a browser?

    Browsers ignore history jumps that go beyond the stack. That is why a Back button needs a fallback when the user may have arrived straight on the page.
  5. 5. Which is the right element for a plain link to /pricing in the navigation bar?

    Link renders a real anchor, so it works with middle click, 'open in new tab', keyboard navigation and assistive technology. navigate is for navigation your code decides on.

Summary

  • useNavigate() returns a function: navigate("/path", options) changes the page from code.
  • Options include replace (overwrite the current entry), state (data for the next page) and relative (path-relative resolution).
  • navigate(-1) and navigate(1) move through the history stack; guard them with a fallback, for example by checking location.key !== "default".
  • Use replace for pages that should not stay in history, such as a submitted form or a login; navigate after the work has succeeded.
  • Prefer Link for clicks, <Navigate> for render-time redirects and redirect() in loaders and actions; avoid navigate inside effects.

Next: Protected Routes and Auth Redirects