Programmatic navigation
- React course
- Intermediate
- Lesson 43/80
- 4 min
Learn to change pages from code with useNavigate.
Programmatic navigation
Sometimes you need to navigate to another page programmatically, after a button click or form submit. Instead of Link you use the useNavigate hook.
const navigate = useNavigate(); gives you a function. navigate('/home') goes to the new path; navigate(-1) goes back one step.
Common uses: redirect after form submit, go to login page after logout, or redirect with a timer.
Using useNavigate
useNavigate returns a function. The first argument can be a path string or a number. The second argument is options: { replace: true } replaces the current history entry instead of pushing a new one.
Example: a logout button using replace: true stops the user from going back to the protected page. With state you can carry data to the next page: navigate('/login', { state: { from: '/panel' } }).
Read this data in the target page via useLocation().state.
Practice Logout button
Complete the skeleton below. Write a LogoutButton component; get navigate with useNavigate and return <button onClick={() => navigate('/login', { replace: true })}>Logout</button>. Export it.
Starter code
import { useNavigate } from "react-router-dom";
// Write the LogoutButton component hereSample solution
import { useNavigate } from "react-router-dom";
function LogoutButton() {
const navigate = useNavigate();
return <button onClick={() => navigate("/login", { replace: true })}>Logout</button>;
}
export default LogoutButton;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does navigate(-1) do?
- Ana sayfaya gider
- Resets the route
- Reloads the page
- Goes back one step Correct answer
Explanation: navigate(-1) goes back one step in history.
2 navigate call
const navigate = ____;
const navigate = useNavigate();
Explanation: useNavigate() returns a function.
3 Programmatic navigation: match the terms
| Term | Meaning |
|---|---|
useNavigate |
Returns a function |
navigate('/x') |
Goes to a path |
navigate(-1) |
Goes back |
{ replace: true } |
Replaces the entry |