Popular Searches
Popular Course Categories
Popular Courses

useNavigate Hook

useNavigate Hook

React Router

React Router useNavigate Hook – Detailed Notes

The useNavigate Hook is a React Router hook that allows developers to navigate programmatically from one route to another. It is useful when navigation needs to happen after an event, such as successful login, form submission, logout, or completion of a task, instead of using a normal navigation link.

Course: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is the useNavigate Hook?

useNavigate() is a hook provided by React Router. It returns a function that can be called to navigate to a different route in a React application without performing a full-page reload.

For example, after a user successfully logs in, the application can automatically navigate them to the dashboard.

Example

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

Explanation:

  • useNavigate() creates a navigation function.
  • navigate("/dashboard") changes the current route to the dashboard.
  • The navigation happens when the user clicks the Login button.

2. Why Do We Use useNavigate?

The useNavigate Hook is helpful when an application needs to change routes based on an event, a result, or a specific condition.

  • Login and authentication: Navigate to a dashboard after successful login.
  • Form submission: Navigate to a success or confirmation page after saving data.
  • Logout: Redirect users to the login page.
  • Shopping applications: Navigate to the order confirmation page after checkout.
  • Multi-step forms: Move users to the next step after validation.
  • Back navigation: Return to a previous page when appropriate.

3. Installing React Router

If React Router is not already installed, install it using npm.

npm install react-router

In current React Router declarative examples, hooks and routing components can be imported from react-router. Existing projects may use react-router-dom, depending on their installed version and setup. Follow the imports supported by your project.


4. Setting Up BrowserRouter

The component that uses useNavigate() must be rendered inside a compatible router. For a basic browser application, you can configure BrowserRouter and define routes with Routes and Route.

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

Important: The routes must match the paths used in calls such as navigate("/about").


5. Basic Syntax of useNavigate

const navigate = useNavigate();
navigate("/about");

The returned navigate function accepts either a destination or a numeric history delta.

Syntax Purpose
navigate("/home") Navigate to the Home route.
navigate("/profile") Navigate to the Profile route.
navigate(-1) Go back one history entry.
navigate(1) Go forward one history entry, if available.
navigate("/login", { replace: true }) Navigate to Login and replace the current history entry.

6. Navigating to Another Page on Button Click

You can use useNavigate() to navigate when a user clicks a button.

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

How it works: When the user clicks the button, the event handler calls navigate("/about"). React Router then displays the component associated with the /about route.


7. Navigating After Form Submission

A common use case is redirecting users after a form has been submitted successfully.

import { useState } from "react";
import { useNavigate } from "react-router";
function Registration() {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    if (name.trim() !== "") {
      // Save or submit the registration data here.
      navigate("/success");
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name:</label>
      <input
        id="name"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <button type="submit">Register</button>
    </form>
  );
}
export default Registration;

Explanation:

  1. The user enters a name.
  2. The form's submit handler prevents the browser's default page reload.
  3. The example checks that the name is not empty.
  4. If the check passes, the app navigates to /success.

Note: This example demonstrates client-side navigation only. A real registration form should validate and save data through an appropriate backend or API before redirecting to the success page.


8. Redirecting After Successful Login

In authentication workflows, navigation often happens after the application confirms that the user's credentials are valid.

import { useNavigate } from "react-router";
function Login() {
  const navigate = useNavigate();
  const handleLogin = async () => {
    // Replace this with your real authentication request.
    const loginSuccessful = true;
    if (loginSuccessful) {
      navigate("/dashboard", { replace: true });
    }
  };
  return (
    <div>
      <h2>Login Page</h2>
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}
export default Login;

Here, replace: true replaces the current history entry. It can help prevent the login page from remaining as the immediately previous entry in browser history, but it does not replace proper authentication or route protection.


9. Using replace: true

The replace option determines whether navigation adds a new history entry or replaces the current one.

Normal Navigation

navigate("/dashboard");

This normally adds a new history entry. The Back button may return to the previous page.

Replace Current History Entry

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

This replaces the current history entry with the dashboard route instead of adding another entry.

Option Behavior Common Use
Default Adds a history entry. Normal page navigation.
replace: true Replaces the current history entry. Some login redirects, temporary routes, and post-submission flows.

10. Going Back and Forward

The navigate function accepts a number to move through the browser's history stack.

Go Back

import { useNavigate } from "react-router";
function BackButton() {
  const navigate = useNavigate();
  return (
    <button onClick={() => navigate(-1)}>
      Go Back
    </button>
  );
}
export default BackButton;

Go Forward

const navigate = useNavigate();
navigate(1);

Important: Use numeric navigation carefully. The browser may not have a previous or next history entry, or the entry may point somewhere unexpected. When the destination is known, navigating to a specific route is often safer.


11. Passing State During Navigation

You can pass temporary state to another route using the state option. The destination component can read it with useLocation().

Sender Component

import { useNavigate } from "react-router";
function Product() {
  const navigate = useNavigate();
  const handleViewDetails = () => {
    navigate("/checkout", {
      state: { productName: "Laptop", quantity: 1 }
    });
  };
  return (
    <button onClick={handleViewDetails}>
      Continue to Checkout
    </button>
  );
}
export default Product;

Destination Component

import { useLocation } from "react-router";
function Checkout() {
  const location = useLocation();
  const checkoutData = location.state;
  return (
    <div>
      <h2>Checkout</h2>
      <p>Product: {checkoutData?.productName ?? "Not provided"}</p>
      <p>Quantity: {checkoutData?.quantity ?? 0}</p>
    </div>
  );
}
export default Checkout;

Important: Navigation state is not a substitute for persistent storage or server-side validation. The destination should handle missing state, because users may open the route directly or refresh the page.


12. Navigating with Query Parameters and Hashes

You can navigate to a route that includes query parameters or a URL hash.

navigate("/products?category=electronics");
navigate("/profile#settings");

To build a destination using separate parts, you can pass a location object:

navigate({
  pathname: "/products",
  search: "?category=electronics",
  hash: "#featured"
});

Query parameters are useful for filters, sorting, search terms, and pagination. A hash can identify a section of a page.


13. Complete Example: Home, About, and Contact Pages

This example demonstrates programmatic navigation among three routes.

import { BrowserRouter, Routes, Route, useNavigate } from "react-router";
function Home() {
  const navigate = useNavigate();
  return (
    <div>
      <h2>Home Page</h2>
      <button onClick={() => navigate("/about")}>About</button>
      <button onClick={() => navigate("/contact")}>Contact</button>
    </div>
  );
}
function About() {
  const navigate = useNavigate();
  return (
    <div>
      <h2>About Page</h2>
      <button onClick={() => navigate("/")}>Home</button>
    </div>
  );
}
function Contact() {
  const navigate = useNavigate();
  return (
    <div>
      <h2>Contact Page</h2>
      <button onClick={() => navigate("/")}>Home</button>
    </div>
  );
}
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
        <Route path="/contact" element={<Contact />} />
      </Routes>
    </BrowserRouter>
  );
}
export default App;

Result: The Home page provides buttons to navigate to About and Contact. Both secondary pages provide a button to return Home.


14. useNavigate vs Link vs NavLink

Feature useNavigate Link NavLink
Type Hook Component Component
Navigation method Programmatic User clicks a link User clicks a link
Typical use After an action or condition Ordinary navigation Navigation with active styling
Example navigate("/home") Home Home

Best practice: Prefer Link or NavLink for ordinary navigation that the user initiates by clicking a link. Use useNavigate() when navigation depends on an event handler, completed operation, or other programmatic condition.


15. Common Mistakes When Using useNavigate

  • Using the hook outside a router: Ensure the component is rendered inside a compatible router.
  • Calling the hook conditionally: Call useNavigate() at the top level of a React component or custom hook, not inside an if statement or event handler.
  • Calling navigate during render: Do not trigger navigation directly while rendering a component. Call it in an event handler or an appropriate effect.
  • Using an undefined route: Confirm that the target path matches a configured route.
  • Assuming state always exists: The destination should handle missing navigation state.
  • Using navigate(-1) without checking the flow: There may be no useful previous history entry.
  • Redirecting before an operation succeeds: Wait for the required validation, API response, or save operation before navigating.
  • Using navigation as security: Hiding a page through client-side navigation alone does not protect private data. Enforce authorization on the server as well.

16. Best Practices

  1. Use useNavigate() for navigation triggered by application logic.
  2. Use Link and NavLink for normal navigational links.
  3. Validate form input before changing routes.
  4. For API-based forms, navigate only after the relevant request succeeds.
  5. Use replace: true only when replacing the current history entry is appropriate.
  6. Handle missing or invalid route state gracefully.
  7. Use meaningful route paths, such as /dashboard and /products.
  8. Follow the API and import conventions of the React Router version installed in your project.

17. Real-World Applications

Application Example Navigation
Login system Successful login to dashboard.
Registration form Completed registration to confirmation page.
E-commerce Successful checkout to order confirmation.
Admin panel After a valid action, navigate to the relevant management page.
Multi-step form Move to the next step after successful validation.
Logout Return to the login page after ending the session.
Quiz application Navigate to the result page when the quiz is completed.

18. Interview Questions and Answers

Q1. What is useNavigate in React?

Answer: useNavigate() is a React Router hook that returns a function for programmatic navigation between routes.

Q2. How do you use useNavigate?

Answer: Import the hook, call it inside a component, and invoke the returned function with the destination path.

const navigate = useNavigate();
navigate("/dashboard");

Q3. What is the difference between navigate("/home") and navigate(-1)?

Answer: navigate("/home") navigates to a specified route, while navigate(-1) moves one entry backward in the browser's history.

Q4. What does replace: true do?

Answer: It replaces the current history entry instead of adding a new one.

Q5. Can useNavigate pass data to another route?

Answer: Yes. You can pass data through the state option and read it from useLocation().state on the destination route.

Q6. Can useNavigate be called outside a React component?

Answer: No. Hooks must be called at the top level of a React function component or a custom hook, within the appropriate router context.

Q7. Should useNavigate be used for every link?

Answer: No. Use Link or NavLink for normal user-facing navigation. Use useNavigate() when navigation needs to happen programmatically.

Q8. Does useNavigate reload the entire webpage?

Answer: In a typical React Router single-page application, navigation between configured client-side routes updates the route without a full-page reload.


19. Practice Exercises

  1. Create a Home page with a button that navigates to an About page.
  2. Create a Login page that navigates to a Dashboard after successful validation.
  3. Create a Registration form that redirects to a Success page after valid submission.
  4. Create a Back button using navigate(-1).
  5. Create a Checkout page and pass product information using navigation state.
  6. Build a three-step form and navigate to the next step after validating each step.
  7. Use replace: true and observe how browser history behaves.

20. Quick Revision Checklist

  • Understand what useNavigate() does.
  • Know how to import and call the hook.
  • Understand programmatic navigation with a destination path.
  • Know how to go back and forward through history.
  • Understand the replace and state options.
  • Know when to use useNavigate versus Link or NavLink.
  • Understand router context and the Rules of Hooks.
  • Practice navigation after form submission and successful login.

21. Official Documentation and Learning Resources


22. React JS Training Resources

Learn React JS concepts, routing, hooks, component development, and practical application building through structured training and demonstrations.

Explore the Course: JustAcademy React JS Training Course

Register for a Demo: Register for React JS Course Demo


Conclusion

The useNavigate Hook is an important React Router feature for programmatic navigation. It allows applications to move users to appropriate routes after events such as login, form submission, checkout, or task completion. Understanding destination paths, history navigation, the replace option, and navigation state helps developers create clear and reliable React applications.

whatsapp