Mastering React Navigation: A Deep Dive into `useNavigate`
In a modern React application, navigation isn't just about clicking links. We often need to change routes based on application logic: after a user logs in, submits a form, or an API call fails. This is called **programmatic navigation**, and in React Router v6, our primary tool for this is the `useNavigate` hook.
The Modern Way: `useNavigate` (React Router v6)
The `useNavigate` hook is a lean, powerful, and intuitive replacement for the older `useHistory` hook. Its usage is simple:
- Import it:
import { useNavigate } from 'react-router-dom'; - Call it at the top level of your component:
const navigate = useNavigate(); - Call the returned `Maps` function to change routes:
navigate('/dashboard'); A
function LoginButton() {
const navigate = useNavigate();
function handleLogin() {
// ... perform login logic
navigate('/dashboard');
}
return <button onClick={handleLogin}>Login</button>;
}Common Use Cases: `push` vs. `replace`
The `Maps` function can do more than just "push" a new route. By default, `Maps('/path')` acts like `history.push`, adding a new entry to the history stack. But its real power comes from its options object.
1. Login/Authentication (The `replace` use case)
When a user logs in, you don't want them to be able to click the browser's "back" button and see the login screen again. To prevent this, you can **replace** the current entry in the history stack.
Maps('/dashboard', { replace: true });This tells React Router to replace `/login` with `/dashboard` in the history, effectively deleting the login page from the session's past.
2. Navigating Back (like `history.goBack`)
The `Maps` hook also simplifies going back and forth in history. You don't need a separate `goBack` function.
- Go back one page:
navigate(-1) - Go forward one page:
navigate(1) - Go back two pages:
navigate(-2)
Advanced: Passing State with Navigation
What if you want to send data to the new route without using URL params? You can pass a `state` object. This is perfect for sending a temporary message, like "You have logged out successfully," to the home page.
// In your Logout component
navigate('/', { state: { message: 'Logged out!' } });
// In your Home component
import { useLocation } from 'react-router-dom';
function Home() {
const location = useLocation();
const message = location.state?.message;
return (
<div>
{message && <p className="success-message">{message}</p>}
{/* ...rest of Home page */}
</div>
);
}The `useLocation` hook gives you access to the `state` object you passed during navigation.
What About `useHistory`? (React Router v5)
If you are working in an older codebase (React Router v5), you will see the `useHistory` hook. It is functionally similar but with a more complex API.
- v5:
const history = useHistory(); history.push('/path'); - v6:
const navigate = useNavigate(); navigate('/path'); - v5 (replace):
history.replace('/path'); A - v6 (replace):
navigate('/path', { replace: true }); - v5 (go back):
history.goBack(); - v6 (go back):
navigate(-1);
The `useNavigate` hook is a clear improvement, consolidating multiple methods into one, more flexible API.
Key Takeaway: Use `useNavigate` for all programmatic navigation in modern React apps. Use `Maps('/path')` for standard navigation and `Maps('/path',{ replace: true })` for scenarios like authentication where you want to modify the history stack.