Sub topic 9
Navigating from code
Links cover navigation that the user starts by clicking. Sometimes your code has to start it: after a login succeeds, after a delete, or when an old URL should point somewhere new. This chapter assumes you know route objects, Link, and the data router setup from earlier chapters.
Three tools, three places
React Router gives you one tool for each place where navigation can start.
| Tool | Where you use it | Typical use |
|---|---|---|
| `useNavigate` | Event handlers and effects | Go to a page after a click or a finished request |
| `<Navigate>` | Component render output | Send the user elsewhere when a component renders |
| `redirect` | Loaders and actions | Leave a route before it renders, or after a mutation |
useNavigate
useNavigate returns a function. Call it with a path to push a new history entry. Call it with a number to move through history, so -1 acts like the browser's back button.
import { useNavigate } from "react-router-dom";
export function LoginForm() {
const navigate = useNavigate();
async function handleSubmit(event) {
event.preventDefault();
const res = await fetch("/api/login", { method: "POST" });
if (res.ok) {
navigate("/dashboard", { replace: true });
}
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Log in</button>
</form>
);
}
export function BackButton() {
const navigate = useNavigate();
return <button onClick={() => navigate(-1)}>Back</button>;
}The option replace: true swaps the current history entry instead of adding one. After a login, this keeps the Back button from returning to the login form.
The Navigate component
<Navigate> navigates as soon as it renders. Use it when the decision comes from what you are rendering, such as a legacy URL.
import { Navigate } from "react-router-dom";
export function OldProfile() {
return <Navigate to="/profile" replace />;
}redirect in loaders and actions
Loaders and actions are plain functions, so hooks are not available there. Return or throw redirect instead. Both forms work. Throwing is useful inside helper functions, because it stops the caller immediately.
import { redirect } from "react-router-dom";
export async function deletePostAction({ params }) {
await fetch(`/api/posts/${params.postId}`, { method: "DELETE" });
return redirect("/posts");
}Common errors
- Calling
navigate()directly in the component body. It runs on every render and triggers a warning or a loop. Put it in a handler or inuseEffect, or use<Navigate>. - Using
redirectin a component. It only creates a response object, so nothing happens unless a loader or action returns or throws it. - Forgetting
replacefor redirects the user did not choose, such as sending a guest to the login page. Without it, Back returns to the page that redirects again. - Navigating after an unfinished request. Wait for
await fetch(...)and checkres.okbefore you callnavigate.
Exercise
A component renders a "Save" button. On click it saves data with fetch, then must send the user to /items without leaving a history entry for the current page. Which tool do you use, and with which option?
Show answer
Use useNavigate inside the click handler, and call navigate("/items", { replace: true }) after the awaited fetch succeeds. A Navigate component would run at render time, and redirect only works in loaders and actions.