What is useNavigate Hook in React Router?
This article provides a comprehensive overview of the
useNavigate hook in React Router, explaining its purpose,
syntax, and practical implementation. You will learn how to navigate
programmatically, pass state data between routes, handle browser history
modification, and perform delta navigation (going back or forward) in
your React applications.
Understanding the useNavigate Hook
The useNavigate hook is a built-in feature of
react-router-dom (introduced in version 6 to replace
useHistory). It returns a function that allows you to
navigate programmatically within your React components. Unlike
traditional link components (<Link>), which require a
user to click an element, useNavigate lets you trigger
redirects in response to events, such as form submissions, API call
completions, or authentication checks.
Basic Syntax and Implementation
To use the useNavigate hook, you must first import it
from react-router-dom and call it inside a functional
component to get the navigate function.
import { useNavigate } from 'react-router-dom';
function LogInButton() {
const navigate = useNavigate();
const handleLogin = () => {
// Perform login logic here
navigate('/dashboard');
};
return (
<button onClick={handleLogin}>
Log In
</button>
);
}In this example, clicking the button triggers the
handleLogin function, which programmatically redirects the
user to the /dashboard path.
Replacing the History Entry
By default, calling the navigate function pushes a new entry onto the
history stack, meaning the user can click the browser’s back button to
return to the previous page. If you want to replace the current entry in
the history stack instead of adding a new one, you can pass an options
object with replace: true.
navigate('/profile', { replace: true });This is particularly useful after successful form submissions or login redirects, preventing users from accidentally resubmitting data when clicking the back button.
Passing State During Navigation
The useNavigate hook allows you to pass data (state) to
the destination route without displaying it in the URL. You can achieve
this by using the state key inside the options object.
const userDetails = { name: 'Alex', role: 'Admin' };
navigate('/user-profile', { state: userDetails });To retrieve this state on the target component, use the
useLocation hook:
import { useLocation } from 'react-router-dom';
function UserProfile() {
const location = useLocation();
const user = location.state;
return (
<div>
<h1>Welcome, {user?.name}</h1>
<p>Role: {user?.role}</p>
</div>
);
}Delta Navigation (Going Back and Forward)
You can also use the navigate function to move backward or forward through the user’s browser history. Instead of passing a string path, pass an integer representing the step delta.
To go back one page:
navigate(-1);To go forward one page:
navigate(1);To go back two pages:
navigate(-2);