Sub topic 9
Navigating from code
Links cover navigation the user starts by clicking. Many transitions come from your code instead: after a login succeeds, after a form saves, when a legacy URL should move to a new one, or when a loader finds the user isn't allowed on the page. React Router gives you three tools for this: the useNavigate hook, the <Navigate> component, and the redirect function.
This chapter assumes you can already build a router with createBrowserRouter, define nested routes, and use Link. It also assumes you know what a loader and an action are, at the level of "functions attached to a route".
Three tools, three places
Each tool works in a different place. Using the wrong one is the most common mistake here.
| Tool | Where it works | Typical use |
|---|---|---|
| `useNavigate()` | Inside a component, in event handlers and effects | After a click, a timer, or an async call in a component |
| `<Navigate to="..." />` | Inside JSX, during render | Declarative redirect, such as a renamed URL |
| `redirect("...")` | Inside a loader or action | Redirect before the route renders, or after a mutation |
useNavigate
useNavigate returns a function. Call it with a path to push a new entry onto the browser history, as a click on a Link would.
import { useNavigate } from "react-router-dom";
function BackButton() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>Back</button>;
}The function accepts three kinds of argument:
- A string path such as
"/users/42"or"/search?q=router". - A number.
navigate(-1)goes back one entry andnavigate(1)goes forward, like the browser buttons. - A location object such as
{ pathname: "/search", search: "?q=router" }.
The second argument is an options object. The two options you will use most are replace and state.
replace
By default, navigate adds a history entry. With { replace: true } it overwrites the current entry instead. Use this when going back to the previous page would be pointless or confusing. After a login, for example, Back should not return the user to the login form.
state
state attaches a value to the history entry. It is not part of the URL, so it is invisible to the user and does not survive being shared as a link. The target page reads it with useLocation.
import { useLocation, useNavigate } from "react-router-dom";
export function Login() {
const navigate = useNavigate();
const location = useLocation();
const from = location.state?.from ?? "/dashboard";
function handleSubmit(event) {
event.preventDefault();
localStorage.setItem("token", "demo-token");
navigate(from, { replace: true });
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Log in</button>
</form>
);
}
// Elsewhere: navigate("/login", { state: { from: "/settings" } });The optional chaining (location.state?.from) matters. A user who opens /login directly has no state, so location.state is null.
Relative navigation
Paths that start with / are absolute. Paths that don't are relative to the route that calls useNavigate. So inside the route users/:userId, navigate("edit") goes to /users/42/edit.
The .. segment moves up one level in the route hierarchy, not one URL segment. This difference matters when a route's path has several segments. Suppose a route is defined as path: "users/:userId". From it, navigate("..") goes to the parent route, which is whatever route contains it. If the parent is the root at /, you land on /, not on /users.
If you want URL-segment behavior, pass the relative option:
navigate("..", { relative: "path" });With relative: "path", .. removes one segment from the current URL, so /users/42 becomes /users. The default is relative: "route". When a relative navigation lands in the wrong place, check which of these two modes you are in.
The Navigate component
<Navigate> navigates as soon as it renders. It is the declarative form of useNavigate, and it is handy for renamed URLs.
import {
createBrowserRouter,
RouterProvider,
Navigate,
} from "react-router-dom";
const router = createBrowserRouter([
{ path: "/about", element: <h1>About</h1> },
{ path: "/about-us", element: <Navigate to="/about" replace /> },
]);
export default function App() {
return <RouterProvider router={router} />;
}Visiting /about-us renders <Navigate>, which replaces that history entry with /about. Without replace, pressing Back would return to /about-us, which would immediately redirect forward again and trap the user.
<Navigate> suits conditions that depend on component state, too:
function Gate({ user, children }) {
if (!user) return <Navigate to="/login" replace />;
return children;
}For a redirect that depends only on the URL or on data you can fetch, a loader is usually better. A loader redirects before the component renders, so nothing flashes on screen.
redirect in loaders and actions
Loaders and actions are plain functions, not components, so hooks don't work in them. redirect returns a Response with a redirect status and a Location header, and the router follows it.
import { redirect } from "react-router-dom";
export async function createContactAction({ request }) {
const formData = await request.formData();
const res = await fetch("/api/contacts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: formData.get("name") }),
});
const contact = await res.json();
return redirect(`/contacts/${contact.id}`);
}You can use either return redirect(...) or throw redirect(...). They behave the same for the router. Use return when the redirect is the normal outcome, as in the action above. Use throw when you are deep inside a helper function and need to stop the caller. In the helper requireAuth, a throw ends the loader before it does any more work.
redirect has no state option, because it works through a response, not a history call. To carry information such as "where the user wanted to go", put it in the query string:
import { redirect } from "react-router-dom";
export function requireAuth({ request }) {
if (!localStorage.getItem("token")) {
const url = new URL(request.url);
const from = url.pathname + url.search;
throw redirect(`/login?from=${encodeURIComponent(from)}`);
}
return null;
}The login page can then read from with useSearchParams and pass it to navigate.
Common errors
- Calling
navigateduring render. Writingnavigate("/login")in the body of a component triggers a warning, because navigation is a side effect. Call it in an event handler or inuseEffect. If it should happen on every render under a condition, render<Navigate>instead. - Using
useNavigatein a loader or action. Hooks work only in components and other hooks. Useredirectthere. - Forgetting to return or throw
redirect. Callingredirect("/x")on its own line just builds a response and discards it. Nothing happens. - Omitting
replaceon redirects the user didn't ask for. A guard or alias that pushes an entry breaks the Back button. - Using
navigate(-1)as a "go to the parent page" link. If the user arrived from another site or a bookmark, Back leaves your app. When you mean "up", navigate to an explicit path. - Expecting
stateto persist as a shareable link. It lives in the history entry, not the URL. Anything the page must have to render correctly belongs in the path or query string.
Exercise
A route's loader checks whether the user is signed in. If not, you want to send them to /login, and after login return them to the page they asked for. Which tool do you use in the loader, how do you pass the original location, and which navigate option should the login page use after success?
Show answer
Use throw redirect(...) in the loader, because hooks like useNavigate don't work there. redirect can't carry state, so put the original path in the query string, for example /login?from=%2Fsettings, built with encodeURIComponent. On the login page, read from with useSearchParams, check that it starts with a single /, and call navigate(from, { replace: true }) so Back doesn't return to the login form.
Exercise
Inside the route users/:userId, which is a child of the root route /, what URL does navigate("..") go to by default, and what option changes it to /users?
Show answer
By default .. is relative to the route hierarchy, so it goes to the parent route, which here is /. Passing { relative: "path" } makes .. remove one URL segment instead, giving /users from /users/42.