Skip to main content

React Router Navigation: useNavigate Hook and Navigate Component

useNavigate Hook

The useNavigate hook allows programmatic navigation in React Router. It is useful when you need to navigate dynamically based on user interactions, such as clicking a button.

  1. Setting Dynamic Params

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

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

    return <button onClick={() => navigate("/post/123")}>Go to Post 123</button>;
    }
  2. Setting Search Params

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

    return <button onClick={() => navigate("/search?query=react")}>Search React</button>;
    }
  3. Setting Fragments

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

    return <button onClick={() => navigate("#contact")}>Go to Contact</button>;
    }

The Navigate component is used to perform navigation declaratively. It can be useful for redirects, such as redirecting users to a login page when they are not authenticated.

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

function ProtectedRoute({ user, children }) {
if (!user) {
return <Navigate to="/login" replace />;
}
return children;
}

In this example, if the user is not authenticated, they will be redirected to the login page.