DEV Community

Cover image for useNavigate in React — Explained Simply with Real Examples
DHANRAJ S
DHANRAJ S

Posted on

useNavigate in React — Explained Simply with Real Examples

Hey!

Tell me if this sounds familiar.

You built a login page in React. User fills in the details, clicks login, and — nothing happens. The page just sits there.

You wanted to send the user to the dashboard after login. But how?

You cannot just use a link — the user did not click anything. The redirect needs to happen from your code, based on logic.

That is exactly what useNavigate solves.


1. What Is useNavigate?

useNavigate is a hook from React Router.

It gives you a function that you can call to move the user to a different page — from inside your code, not from a link they click.

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

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

  function handleClick() {
    navigate("/dashboard");
  }

  return <button onClick={handleClick}>Go to Dashboard</button>;
}
Enter fullscreen mode Exit fullscreen mode

useNavigate() returns a function. You store it in navigate. Then you call navigate("/path") whenever you want to go somewhere.

Simple as that.


2. Before You Use It — Set Up React Router

useNavigate only works if React Router is set up properly.

Install it first:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Wrap your app with BrowserRouter in main.jsx:

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

ReactDOM.createRoot(document.getElementById("root")).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);
Enter fullscreen mode Exit fullscreen mode

Define your routes in App.jsx:

import { Routes, Route } from "react-router-dom";

function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/login" element={<Login />} />
      <Route path="/dashboard" element={<Dashboard />} />
    </Routes>
  );
}
Enter fullscreen mode Exit fullscreen mode

Done. Now useNavigate will work inside any component in your app.


3. Basic Syntax — What Can You Do With navigate?

const navigate = useNavigate();

navigate("/about");    // go to about page
navigate(-1);          // go back — like browser back button
navigate(1);           // go forward
navigate("/dashboard", { replace: true }); // go without adding to history
Enter fullscreen mode Exit fullscreen mode

Quick question for you.

What do you think navigate(-1) does?

It takes the user back to the previous page — exactly like pressing the back button in the browser. No need to know the path. React Router figures it out from the history.


4. Link vs useNavigate — Which One to Use?

This confuses a lot of beginners. Both do navigation. So what is the difference?

Link useNavigate
Who triggers it The user clicks it Your code triggers it
Best for Navbar, menu links After login, form submit
Visible on screen Yes — shows as a link No — runs in background

The simple rule:

If the user is clicking to go somewhere — use <Link>.

If your code needs to redirect based on logic — use useNavigate.


5. Example 1 — Login and Redirect

User logs in. Credentials are correct — go to dashboard. Wrong — show an error.

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

function Login() {
  const navigate = useNavigate();
  const [error, setError] = useState("");

  function handleLogin(e) {
    e.preventDefault();

    const username = e.target.username.value;
    const password = e.target.password.value;

    if (username === "admin" && password === "1234") {
      navigate("/dashboard");
    } else {
      setError("Wrong username or password");
    }
  }

  return (
    <div>
      <h2>Login</h2>
      <form onSubmit={handleLogin}>
        <input name="username" placeholder="Username" />
        <input name="password" type="password" placeholder="Password" />
        <button type="submit">Login</button>
      </form>
      {error && <p style={{ color: "red" }}>{error}</p>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Walk through what happens:

User types username and password
  → clicks Login
  → handleLogin runs
  → if correct → navigate("/dashboard") fires
  → user lands on dashboard page

  → if wrong → setError runs
  → error message shows below the form
Enter fullscreen mode Exit fullscreen mode

Navigation only happens when the condition is met.

That is the whole point — logic first, then navigate.


6. Example 2 — Go Back Button

You are on a product detail page. You want a back button that takes the user to wherever they came from.

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

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

  return (
    <div>
      <button onClick={() => navigate(-1)}>Go Back</button>
      <h2>Product Detail Page</h2>
      <p>Here are the product details...</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

navigate(-1) goes back one step in browser history.

No hardcoded path needed. You do not need to know where the user came from. React Router handles it.


7. replace: true — Controlling Browser History

By default — every time you navigate, a new page is added to browser history.

So the user can press back and return to where they were.

But sometimes you do not want that.

After login — you do not want the user pressing back and landing on the login page again.

// Default — adds to history, user can press back
navigate("/dashboard");

// replace: true — replaces the current page, no going back
navigate("/dashboard", { replace: true });
Enter fullscreen mode Exit fullscreen mode

With replace: true — the login page is replaced by dashboard in the history. Back button will not take them to login.

Quick question for you.

Can you think of another case where replace: true is useful?

A payment success page. After paying — you do not want the user pressing back and submitting the payment again. replace: true prevents that.


8. Passing Data While Navigating

Sometimes you want to send some data to the next page without putting it in the URL.

// Send data with navigate
navigate("/profile", { state: { name: "Ravi", userId: 101 } });
Enter fullscreen mode Exit fullscreen mode
// Read it on the next page using useLocation
import { useLocation } from "react-router-dom";

function Profile() {
  const location = useLocation();
  const { name, userId } = location.state;

  return <p>Welcome {name}. Your ID is {userId}.</p>;
}
Enter fullscreen mode Exit fullscreen mode

You pass a state object as the second argument to navigate.

On the next page — useLocation() gives you access to that state.

Clean. Simple. No URL clutter.


9. One Mistake Everyone Makes

Using useNavigate without wrapping the app in BrowserRouter.

// Wrong
ReactDOM.createRoot(document.getElementById("root")).render(
  <App />
);
Enter fullscreen mode Exit fullscreen mode

You will get this error:

useNavigate() may be used only in the context of a <Router> component.
Enter fullscreen mode Exit fullscreen mode
// Right
ReactDOM.createRoot(document.getElementById("root")).render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);
Enter fullscreen mode Exit fullscreen mode

If you ever see that error — go to main.jsx and check if BrowserRouter is wrapping your app. That is almost always the fix.


Quick Summary — 5 Things to Remember

  1. useNavigate returns a function — store it in navigate and call it with a path.

  2. Use it for logic-based navigation — after login, form submit, or any condition. Not for regular links.

  3. navigate(-1) goes back — uses browser history, no path needed.

  4. replace: true — replaces the current page in history so the user cannot press back to return.

  5. Must be inside a Router — always wrap your app with BrowserRouter. Otherwise it throws an error.


useNavigate feels small — but you will use it in almost every React app you build.

Login flows. Form submissions. Protected routes. It comes up everywhere.

Try building the login example. Enter the wrong password and see the error. Enter the right one and watch the redirect happen. That is the best way to make it click.

Got a question? Drop it in the comments below.


Thanks for reading. Keep building.

Top comments (0)