React useNavigate Hook

Introduction

React applications usually use React Router for navigation. Earlier versions of React Router used the useHistory() hook for programmatic navigation. However, React Router Version 6 introduced a new and improved hook called useNavigate().

The useNavigate() hook allows developers to navigate between pages programmatically without using the Link component.

What is useNavigate Hook?

useNavigate() is a React Router hook used for programmatic navigation in React applications.

It allows developers to change routes using JavaScript code instead of clicking links.

The hook returns a function that helps navigate to different pages.

Why useNavigate is Used?

The Link component is useful for normal navigation, but sometimes navigation needs to happen automatically.

Examples:

  • Redirect after successful login
  • Redirect after form submission
  • Navigate after API response
  • Back button functionality
  • Logout redirection

This is where useNavigate() becomes useful.

Installing React Router

Before using useNavigate(), install React Router.


npm install react-router-dom

Importing useNavigate


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

Syntax of useNavigate


const navigate = useNavigate();
After creating the navigate function:
navigate("/about");

This redirects the user to the About page.

Basic Example of useNavigate

Step 1: Create Pages

Home.js


function Home() {
 return <h1>Home Page</h1>;
}
export default Home;

About.js


function About() {
 return <h1>About Page</h1>;
}
export default About;

Step 2: Configure Routes

App.js


import {
 BrowserRouter,
 Routes,
 Route
} from "react-router-dom";
import Home from "./Home";
import About from "./About";
function App() {
 return (
   <BrowserRouter>
     <Routes>
       <Route path="/" element={<Home />} />
       <Route path="/about" element={<About />} />
     </Routes>
   </BrowserRouter>
 );
}
export default App;

Step 3: Use useNavigate Hook

Home.js


import { useNavigate } from "react-router-dom";
function Home() {
 const navigate = useNavigate();
 const goToAbout = () => {
   navigate("/about");
 };
 return (
   <div>
     <h1>Home Page</h1>
     <button onClick={goToAbout}>
       Go to About
     </button>
   </div>
 );
}
export default Home;

How useNavigate Works?

When the button is clicked:

  1. goToAbout() function runs
  2. navigate(“/about”) executes
  3. URL changes to /about
  4. About component renders

No page reload occurs.

Navigate to Dynamic Routes

You can navigate using dynamic values.

Example


navigate(`/user/${id}`);
If id = 5, the URL becomes:
/user/5

Passing State with useNavigate

You can pass data while navigating.

Example


navigate("/profile", {
 state: {
   username: "John"
 }
});

Accessing Passed State

React Router provides useLocation() hook.

Example


import { useLocation } from "react-router-dom";
function Profile() {
 const location = useLocation();
 return (
   <h1>
     {location.state.username}
   </h1>
 );
}
export default Profile;

Navigation Back and Forward

useNavigate() can move through browser history.

Go Back


navigate(-1);

Go Forward


navigate(1);

Replace Current Route

Sometimes developers do not want users to return to the previous page.

Example:

  • Login page after authentication

Example


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

This replaces the current history entry.

Real-Life Example: Login Redirect

Login Component


import { useNavigate } from "react-router-dom";
function Login() {
 const navigate = useNavigate();
 const handleLogin = () => {
   // Login success
   navigate("/dashboard");
 };
 return (
   <button onClick={handleLogin}>
     Login
   </button>
 );
}
export default Login;

Real-Life Example: Form Submission


import { useNavigate } from "react-router-dom";
function ContactForm() {
 const navigate = useNavigate();
 const handleSubmit = (e) => {
   e.preventDefault();
   // Form submission logic
   navigate("/success");
 };
 return (
   <form onSubmit={handleSubmit}>
     <button type="submit">
       Submit
     </button>
   </form>
 );
}
export default ContactForm;

Difference Between Link and useNavigate

Feature Link useNavigate
Navigation Type UI-based Programmatic
Used Inside JSX JavaScript functions
Trigger User click Function call
Common Usage Navigation menus Redirects

useNavigate vs useHistory

React Router v6 replaced useHistory() with useNavigate().

useHistory useNavigate
React Router v5 React Router v6
history.push() navigate()
history.replace() navigate(path, { replace: true })
Older API Simpler API

Advantages of useNavigate

1. Programmatic Navigation

Navigation through JavaScript logic.

2. Easy Redirection

Useful after login or API success.

3. History Navigation

Can move backward and forward.

4. Cleaner Code

Simplifies routing logic.

5. Better User Experience

Provides smooth SPA navigation.

Common Mistakes

1. Using useNavigate Outside Router

Wrong:


const navigate = useNavigate();
without BrowserRouter.

Correct:


<BrowserRouter>

2. Forgetting to Call navigate Function

Wrong:


navigate;

Correct:


navigate("/about");

3. Using useHistory in React Router v6

Wrong:


useHistory();

Correct:


useNavigate();

4. Incorrect Path

Wrong:


navigate("about");

correct:


navigate("/about");

5. Forgetting replace Option Usage

Without replace: true, users can return to previous pages.

Best Practices

Use Meaningful Routes

Good:


/dashboard
/profile
/settings

Bad:


/d1
/p1
/s1

Use replace for Authentication

Prevent users from returning to login pages.

Use Dynamic Routes Properly

Helpful for user profiles and products.

Combine with API Calls Carefully

Navigate only after successful responses.

Advanced Example with API Call


import { useNavigate } from "react-router-dom";
function Register() {
 const navigate = useNavigate();
 const registerUser = async () => {
   const response = await fetch("/api/register");
   if (response.ok) {
     navigate("/login");
   }
 };
 return (
   <button onClick={registerUser}>
     Register
   </button>
 );
}
export default Register;

Conclusion

The useNavigate() hook is one of the most important hooks in React Router. It enables developers to navigate programmatically between pages without reloading the application.

Benefits of useNavigate():

  • Cleaner navigation logic
  • Better user experience
  • Smooth SPA routing
  • Easy route management

Modern React applications heavily rely on useNavigate() for handling navigation efficiently.

Continue Learning React