Course contentsShow
← React
Lesson 1856 of 2,39643. RoutingFree lesson

Programmatic Navigation with useNavigate

Use useNavigate to redirect users in response to events like form submissions or authentication changes.

Programmatic Navigation with useNavigate

What you'll learn: How to redirect users in code (not through link clicks) using React Router's useNavigate hook.

The Core Idea

Sometimes you need to navigate users to a different route in response to code logic rather than a user clicking a link. For example, after a successful form submission, you might want to redirect to a confirmation page. Or after authentication fails, send them back to login. The useNavigate hook gives you a function that programmatically changes the route.

Think of it like this: <Link> is the user pressing a button to go somewhere, while useNavigate is your code deciding "you need to go there now" based on what just happened.

Basic Usage

import { useNavigate } from 'react-router-dom';

function LoginForm() {
  const navigate = useNavigate();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const success = await authenticateUser(credentials);
    
    if (success) {
      // Redirect to dashboard after successful login
      navigate('/dashboard');
    } else {
      // Stay on login, show error
      setError('Invalid credentials');
    }
  };

  return <form onSubmit={handleSubmit}>...</form>;
}

You can also navigate backwards like a browser back button:

navigate(-1); // Go back one page

Or replace the current history entry (so back button won't return here):

navigate('/dashboard', { replace: true });

Common Use Cases

  • Post-submission redirects: After creating a resource, send users to the new item's detail page
  • Authentication flows: Redirect to login when tokens expire, or to protected content after successful auth
  • Multi-step wizards: Move to the next step programmatically after validation passes
  • Conditional routing: Based on user permissions or data, route to different destinations

Key Takeaway: useNavigate gives you a function to change routes programmatically in response to events, side effects, or application logic—essential for redirects after actions like form submissions or authentication checks.