In React Router, useNavigate is a hook that provides imperative navigation capabilities. It allows you to programmatically navigate to different routes within your application without needing to interact with the rendered UI components (like Link or NavLink). This is useful in scenarios where you want to redirect a user after an action, such as form submission, authentication, or any custom logic.

Key Features of useNavigate:

  1. Programmatic Navigation: Allows you to navigate to different routes based on actions or events, like button clicks or form submissions.
  2. History Manipulation: You can push new entries to the navigation stack or replace the current entry in the history, controlling how users navigate back.
  3. Relative or Absolute Navigation: You can navigate to absolute paths or use relative paths based on the current route.

Basic Example:

Here’s how you can use useNavigate to navigate programmatically:

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

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

  const goToAboutPage = () => {
    navigate("/about");  // Navigates to the /about page
  };

  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={goToAboutPage}>Go to About Page</button>
    </div>
  );
}

export default HomePage;

In this example:

  • The useNavigate hook returns a navigate function.
  • When the button is clicked, the navigate("/about") function is triggered, taking the user to the /about route.

Pushing and Replacing History:

  • Push (default behavior): When you use navigate, it pushes a new entry onto the browser’s history stack. The user can go back to the previous page using the browser’s back button.
navigate("/dashboard");  // Adds a new entry to the history stack.
  • Replace: If you want to replace the current entry in the history stack, you can pass { replace: true } as an option.
navigate("/login", { replace: true });  // Replaces the current entry.

Passing State:

You can pass additional state when navigating to a new route. This state can be accessed in the destination route.

navigate("/profile", { state: { userId: 123 } });

On the destination page, you can access the state like this:

import { useLocation } from "react-router-dom";

function ProfilePage() {
  const location = useLocation();
  const userId = location.state?.userId;

  return <div>Profile of User: {userId}</div>;
}

You can also use navigate(-1) to go back to the previous page, similar to the browser’s back button.

navigate(-1);  // Go back one page in the history.

Example with Form Submission:

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

  const handleSubmit = (event) => {
    event.preventDefault();
    // Perform login logic
    navigate("/dashboard");  // Redirect to the dashboard after login
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Username" />
      <input type="password" placeholder="Password" />
      <button type="submit">Login</button>
    </form>
  );
}

In this example, after submitting the form, the user is redirected to the /dashboard route.

navigate(to, { replace, state, relative });
  • to: The path to navigate to.
  • replace: (optional) If true, the navigation replaces the current entry in the history stack.
  • state: (optional) Allows passing state to the target route.
  • relative: (optional) If set, it allows relative navigation based on the current route.

Summary:

  • useNavigate is a hook used for programmatic navigation in React Router.
  • It allows you to navigate to different routes in response to events like form submissions, button clicks, or custom logic.
  • You can push new entries to the history, replace current entries, and pass state to the target route.

This hook makes routing logic more flexible and gives you control over user navigation.