Popular Searches
Popular Course Categories
Popular Courses

useNavigate Hook

useNavigate Hook

React Router

useNavigate Hook in React JS

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 or application action, such as successful form submission, login, logout, or clicking a custom navigation button.

For example, after a user successfully logs in, an application can use useNavigate() to redirect the user to the dashboard without requiring them to click a separate link.

Learn more through JustAcademy React JS Training or Register for React JS Course Demo.


1. What Is the useNavigate Hook?

useNavigate() is a Hook provided by React Router. It returns a navigation function that can be called to change the current route programmatically.

Instead of using a regular anchor tag for every navigation action, you can call the returned function when a specific event occurs.

Example

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

When the user clicks the button, React Router navigates to the /about route, provided that the route is configured in the application.

Note: Current React Router documentation uses imports from react-router. Many existing projects use react-router-dom, depending on the installed version. Use the import path supported by your project.


2. Why Do We Use useNavigate?

The useNavigate Hook is useful when an application needs to control navigation based on a particular action or condition.

  • Login redirection: Navigate to a dashboard after successful authentication.
  • Form submission: Redirect users to a confirmation or success page after saving data.
  • Logout: Navigate users to the login page after logging out.
  • Custom buttons: Create buttons that navigate to other pages.
  • Back and forward navigation: Move through browser history when appropriate.
  • Conditional navigation: Navigate based on application logic.
  • Multi-step workflows: Move users between steps in a process.

For ordinary navigation links, React Router generally recommends using Link or NavLink. The useNavigate Hook is particularly useful when navigation is triggered by application logic or an event handler.


3. Syntax of the useNavigate Hook

The basic syntax involves calling useNavigate() inside a React function component.

const navigate = useNavigate();

Then call the returned function with the destination path.

navigate("/dashboard");

You can also pass options to change how navigation behaves.

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

The replace: true option replaces the current history entry rather than adding a new one.


4. Step-by-Step Implementation

Step 1: Install React Router

If React Router is not installed in your project, install the package used by your chosen version and setup.

npm install react-router

Some projects use react-router-dom, especially older browser-based setups. Check your installed version before choosing the package import.

Step 2: Create a component

Create a file named Home.jsx and add the useNavigate Hook.

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

Step 3: Configure routes

Use BrowserRouter, Routes, and Route to configure the pages.

import { BrowserRouter, Routes, Route } from "react-router";
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 4: Create the About page

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

Step 5: Run and test

  • Start the React development server.
  • Open the home page in the browser.
  • Click the Go to About button.
  • Confirm that the URL changes to /about and the About page appears.

5. Navigating to a Specific Route

The simplest use of useNavigate is to pass a string containing the destination path.

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

Other examples include:

navigate("/");
navigate("/contact");
navigate("/products");
navigate("/users/101");

Each destination must match a route configured in the application, or the application should have an appropriate fallback route.


6. Using useNavigate After Form Submission

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

import { useState } from "react";
import { useNavigate } from "react-router";
function ContactForm() {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const handleSubmit = (event) => {
    event.preventDefault();
    if (!name.trim()) {
      return;
    }
    // Save the form 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">Submit</button>
    </form>
  );
}
export default ContactForm;

This example navigates to /success after basic validation. In a real application, wait until the server confirms that the data has been saved successfully before navigating.


7. Using useNavigate After Login

After a successful login, an application may redirect the user to a protected dashboard.

import { useNavigate } from "react-router";
function Login() {
  const navigate = useNavigate();
  const handleLogin = async () => {
    // Replace this with your actual 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;

Important: The example uses a placeholder boolean for demonstration. A real application must verify the authentication result with its authentication system. Navigation alone does not secure a protected page.


8. Navigating Backward and Forward

The navigate function can accept a number representing a movement through the browser's history stack.

Go back one entry

navigate(-1);

Go forward one entry

navigate(1);

Example Back Button

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

History navigation can be useful for detail pages, modal workflows, and multi-step processes. However, use it carefully because a page may have been opened directly without a previous in-app history entry.


9. Understanding the replace Option

By default, navigating to a new route generally adds a new entry to the browser's history. The replace option replaces the current history entry instead.

Default navigation

navigate("/dashboard");

The current page typically remains in browser history, so the Back button can return to it.

Replace current history entry

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

The current history entry is replaced with the destination. This can be useful after login or when redirecting away from a temporary route that should not remain in the navigation history.

Feature Default navigation Navigation with replace
Syntax navigate("/home") navigate("/home", { replace: true })
History behavior Usually adds a new entry Replaces the current entry
Typical use Moving to another page Redirects where returning to the previous entry is undesirable

10. Passing State During Navigation

React Router allows you to pass optional state to the destination route. This can be useful when you need to send temporary information without adding it to the URL.

Sending state

navigate("/profile", {
  state: {
    username: "Aarav",
    role: "Developer"
  }
});

Reading state on the destination page

import { useLocation } from "react-router";
function Profile() {
  const location = useLocation();
  const user = location.state;
  return (
    <div>
      <h2>Profile Page</h2>
      <p>Username: {user?.username || "Guest"}</p>
      <p>Role: {user?.role || "Not provided"}</p>
    </div>
  );
}
export default Profile;

State may be unavailable when someone opens the destination URL directly. Always provide a fallback when the destination page depends on navigation state. Do not put passwords, secrets, or sensitive information in navigation state.


11. Navigating with Query Parameters

Query parameters can be included in the destination URL to represent search terms, filters, sorting options, or pagination.

navigate("/products?category=books&page=2");

The destination component can read these values using useSearchParams().

import { useSearchParams } from "react-router";
function Products() {
  const [searchParams] = useSearchParams();
  const category = searchParams.get("category");
  const page = searchParams.get("page");
  return (
    <div>
      <p>Category: {category}</p>
      <p>Page: {page}</p>
    </div>
  );
}
export default Products;

For a URL such as /products?category=books&page=2, the component reads the category as books and the page as 2.


12. Difference Between useNavigate, Link, and NavLink

React Router provides different tools for navigation. Choose the one that best matches the interaction.

Feature useNavigate Link NavLink
Type Hook Component Component
Navigation method Programmatic function call User follows a link User follows a link with active-state support
Typical use After form submission or application logic Normal page navigation Navigation menus with active styling
Example navigate("/about") <Link to="/about">About</Link> <NavLink to="/about">About</NavLink>

Best practice: Prefer Link or NavLink for ordinary clickable navigation links. Use useNavigate when navigation depends on an event, a successful operation, or application logic.


13. Common Mistakes and Solutions

Mistake Reason Solution
Calling useNavigate outside a component React Hooks must follow the Rules of Hooks. Call it at the top level of a React function component or custom Hook.
Using it outside Router context The component cannot access the required router context. Render the component inside the configured Router.
Incorrect destination path The path does not match a configured route. Check the route definitions and destination spelling.
Navigating before saving data The operation may not have completed. Wait for the required asynchronous operation to succeed.
Using navigate(-1) without checking history The user may not have a suitable previous history entry. Provide a safe fallback when necessary.
Expecting state to always exist The destination can be opened directly. Handle missing location state and provide default values.
Using navigation as security Changing routes does not enforce server-side authorization. Protect sensitive routes and data with proper authentication and authorization.

14. Best Practices for useNavigate

  • Call useNavigate() only at the top level of a React function component or custom Hook.
  • Use a configured Router such as BrowserRouter or another appropriate router.
  • Use Link and NavLink for normal navigation whenever possible.
  • Use navigation after an operation has completed successfully.
  • Use replace: true only when replacing the current history entry is appropriate.
  • Handle missing navigation state and invalid destination data.
  • Validate authentication and permissions independently of route navigation.
  • Use relative paths carefully, especially when working with nested routes.
  • For React Router data-router actions and loaders, consider using redirect where appropriate.

15. Mini Project: Login and Dashboard Navigation

Objective: Create a small application with a login page, dashboard page, and logout button using useNavigate.

App.jsx

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

Login.jsx

import { useState } from "react";
import { useNavigate } from "react-router";
function Login() {
  const navigate = useNavigate();
  const [username, setUsername] = useState("");
  const handleLogin = (event) => {
    event.preventDefault();
    if (!username.trim()) {
      return;
    }
    // Demonstration only; replace with real authentication.
    navigate("/dashboard", {
      state: { username },
      replace: true
    });
  };
  return (
    <form onSubmit={handleLogin}>
      <h2>Login</h2>
      <input
        value={username}
        onChange={(event) => setUsername(event.target.value)}
        placeholder="Enter username"
      />
      <button type="submit">Login</button>
    </form>
  );
}
export default Login;

Dashboard.jsx

import { useLocation, useNavigate } from "react-router";
function Dashboard() {
  const navigate = useNavigate();
  const location = useLocation();
  const username = location.state?.username || "Guest";
  const handleLogout = () => {
    navigate("/", { replace: true });
  };
  return (
    <div>
      <h1>Welcome, {username}!</h1>
      <p>You are viewing the dashboard.</p>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}
export default Dashboard;

Expected result: Enter a username on the login page and submit the form. The application navigates to the dashboard and displays the username. Clicking Logout returns to the login page.

Project note: This is a navigation demonstration, not a secure authentication system. In a real project, authenticate the user through a backend or identity provider and enforce access permissions for protected data.


16. Interview Questions and Answers

Q1. What is the useNavigate Hook?

Answer: useNavigate is a React Router Hook that returns a function for programmatically navigating to another route or moving through the browser history.

Q2. How do you navigate to another page?

Answer: Call the returned function with a destination path, such as navigate("/dashboard").

Q3. How can you navigate backward?

Answer: Call navigate(-1) to move back one entry in the browser history when a suitable entry exists.

Q4. What does replace: true do?

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

Q5. Can useNavigate be used after form submission?

Answer: Yes. It can navigate to a confirmation page after the form data has been successfully processed.

Q6. What is the difference between useNavigate and Link?

Answer: useNavigate performs navigation programmatically, while Link provides a clickable navigation link. Link is generally preferable for ordinary page navigation.

Q7. Can useNavigate pass data to another route?

Answer: Yes. It can pass state through the options object. The destination can read the state using useLocation().

Q8. Can useNavigate be called inside a normal event handler?

Answer: The Hook itself must be called at the top level of the component. The navigation function it returns can be called inside an event handler.

Q9. Can useNavigate protect a dashboard from unauthorized users?

Answer: No. Navigation is not a security mechanism. The application must enforce authentication and authorization separately.

Q10. When might redirect be preferred over useNavigate?

Answer: In React Router data-router actions and loaders, using redirect is often a better fit for navigation that results from route-level data or form processing.


17. Practice Exercises

  1. Create a Home page with a button that navigates to an About page.
  2. Create a login form that navigates to a dashboard after successful validation.
  3. Create a Back button using navigate(-1).
  4. Navigate to a product details route such as /products/101.
  5. Pass a username through navigation state and display it on the next page.
  6. Use replace: true and observe how browser history behaves.
  7. Create a form that navigates to a success page only after a simulated save operation succeeds.

18. Quick Revision Checklist

  • Understand the purpose of useNavigate.
  • Know how to import and call the Hook.
  • Navigate to a route using a path string.
  • Understand backward and forward navigation.
  • Know how the replace option works.
  • Pass and read state between routes.
  • Use query parameters when appropriate.
  • Understand the differences between useNavigate, Link, and NavLink.
  • Handle failed operations and missing state correctly.
  • Remember that navigation does not replace authentication or authorization.

19. Conclusion

The useNavigate Hook is an important React Router feature that enables programmatic navigation. It is especially useful for login flows, form submissions, logout actions, custom buttons, and other application-driven navigation scenarios. By learning how to navigate to routes, move through browser history, replace history entries, and pass state, developers can build more flexible React applications.

Continue learning with JustAcademy React JS Training or Register for React JS Course Demo.

Official References

Previous Next
whatsapp