Is a React Hook that gives access to the navigate object.
we can't pass navigate object directly as a props to the component,don't want to pass it in deeply child
Is a Standard way to programmatically change routes within a functional component,Replacing the deprecated useHistory Hook
Returns a function that navigate programmatically in browser in response to user interaction or effect
Returns the current Navigation action which describes how the router came to the current Location, either by a pop, push, or replace on the History stack.
to navigate between different pages in your app. It replaces the older useHistory() hook.
Send data or parameters when moving to another page.
function useNavigate(): NavigateFunction
Returns
A navigate function for programmatic navigation
How to use useNavigate
1.Import the Hook
import {useNavigate} from "react-router-dom";
2.Initialize
Call the Hook at the top level of component to get the Navigate function
3.Execute Navigation
Trigger the function within event handlers or useEffect block
Use Cases
Basic Path Navigation
To move to a specific URL,pass the path as a string.
const navigate = useNavigate();
// ... inside an event handler
navigate("/dashboard");
History Delta
To go forward or back in history,pass a number(eg.,-1 to go back one page)
Replacing State
Use {replace: true} to update the current entry in the history stack instead of adding a new one.
Passing state
pass optional data to the destination route using the state property
navigate("/profile", { state: { userId: 123 } });
Navigate to another path
navigate("/some/route");
navigate("/some/route?search=param");
Navigate with a To object
All properties are optional.
navigate({
pathname: "/some/route",
search: "?search=param",
hash: "#hash",
state: { some: "state" },
});
use state,that will be available on the Location object on the next page.Access it useLocation().state
Navigate back or forward in the history stack
// back
// often used to close modals
navigate(-1);
// forward
// often used in a multistep wizard workflows
navigate(1);
Use this you are sure ,have an entry in the History stack to navigate to.
Replace the current entry in the history stack
Remove the current entry in the History stack, replacing it with a new one, similar to a server side redirect.
navigate("/some/route", { replace: true });
Prevent Scroll Reset
To prevent from resetting the scroll position, use the preventScrollReset option.
navigate("?some-tab=1", { preventScrollReset: true });
For example, if you have a tab interface connected to search params in the middle of a page, and you don't want it to scroll to the top when a tab is clicked.
Return Type Augmentation
In React Router, the useNavigate() function is used to move (navigate) from one page to another.
But internally, it behaves differently in two modes:
Normal mode (BrowserRouter)
→ Navigation happens immediately
→ It returns nothing (void)
Advanced mode (Data / Framework mode using RouterProvider)
→ Navigation is asynchronous (takes time)
→ It returns a Promise (something you can await)
So what’s the problem?
Because of these two behaviors, TypeScript thinks:
useNavigate() returns: void OR Promise
This confuses TypeScript and causes errors like:
“You didn’t handle a promise” (no-floating-promises)
Type mismatch errors
Simple meaning of the solution
You are telling TypeScript:
“Hey, I know which mode I am using. So use the correct return type.”
Fix for each case
If you are using BrowserRouter:
Navigation is simple → no Promise
useNavigate() → returns void
So you tell TypeScript:
declare module "react-router" {
interface NavigateFunction {
(to: To, options?: NavigateOptions): void;
(delta: number): void;
}
}
If you are using RouterProvider (Framework/Data mode):
Navigation is async → returns Promise
useNavigate() → returns Promise
So you tell TypeScript:
declare module "react-router" {
interface NavigateFunction {
(to: To, options?: NavigateOptions): Promise<void>;
(delta: number): Promise<void>;
}
}
Final simple idea
React Router gives two possible return types
TypeScript gets confused
You fix it by clearly telling TypeScript what to expect
Using with class component
You can wrap your class component in a function component to use the hook:
class MyBackButton extends React.Component {
render() {
// Get it from props
const { navigation } = this.props;
}
}
// Wrap and export
export default function (props) {
const navigation = useNavigation();
return <MyBackButton {...props} navigation={navigation} />;
}
What is useNavigate()?
useNavigate() is a hook in React Router.
It gives you a function that helps you move from one page to another in your app.
Why do we use it?
You use it when:
A user clicks a button
A form is submitted
Something happens in your code (like login success)
let navigate = useNavigate();
Now navigate is a function you can use.
How to use it?
- Go to another page
navigate("/home");
Moves to /home page
- Go back / forward
navigate(-1); // go back
navigate(1); // go forward
What are “options”?
You can control navigation using extra settings.
Example:
navigate("/home", { replace: true });
Common options **
**replace
Replaces current page (no back button history)
state
Send extra data to next page
relative
Helps with relative paths (advanced usage)
Advanced options (only in special modes)
flushSync
Forces immediate update (rarely used)
preventScrollReset
Stops page from scrolling to top after navigation
viewTransition
Adds smooth animation between pages
Important note
Instead of useNavigate(), sometimes it's better to use:
redirect() (inside loaders/actions)
Because:
It’s cleaner
Works better with data fetching
*Example *
function SomeComponent() {
let navigate = useNavigate();
return (
<button onClick={() => navigate(-1)}>
Go Back
</button>
);
}
When button is clicked → it goes back to previous page
SUMMARY
useNavigate() = move between pages using code
navigate("/path") → go to page
navigate(-1) → go back
options → control how navigation behaves
Implementation of useNavigate() Hook
Step 1: To start with, create a React application
npm create vite@latest demo
Step 2: Move to the project directory.
cd demo
Step 3: Install the latest version of react-router-dom in the React application
npm install react-router-dom@6
How to Use useNavigate() for Navigation?
Step 1: Install React Router
npm install react-router-dom@6
Step 2: Import the useNavigate Hook
import the useNavigate hook from react-router-dom.
import { useNavigate } from 'react-router-dom';
Step 3: Call useNavigate() Inside Your Component
Inside your functional component, call useNavigate() to access the navigate function. This function will allow you to programmatically change the route.
const navigate = useNavigate();
Step 4: Use navigate() to Change Routes
navigate('/path'); // Navigates to '/path'
Step 5: Using replace for One-Time Redirection
use the { replace: true } option to replace the current history entry. This is useful for cases like login redirects, where you don’t want users to be able to use the back button to return to the previous page.
navigate('/path', { replace: true });
Step 6: Navigating Back and Forward
To navigate back in the browser’s history, use a negative number (e.g., -1), and to move forward, use a positive number (e.g., 1):
navigate(-1); // Goes back one step in historynavigate(1); // Goes forward one step in history
App.js: Sets up routing with BrowserRouter, defining routes for / (Home) and /about (About).
Home.js: Displays "GeeksForGeeks" and a button to navigate to the /about page using useNavigate().
About.js: Displays a message and a button to go back to the home page using useNavigate(-1).
Navigation Flow: Clicking "About" takes you to /about, and "Go Back Home" takes you back to /.
useNavigate(): Used to navigate programmatically between routes in both Home and About.
When to Use useNavigate() vs.
useNavigate(): Best suited for programmatic navigation triggered by code, such as after form submissions, authentication events, or specific actions that aren't directly related to user interaction.
or : Ideal for declarative navigation, where the route change is a part of the UI and driven by user interaction, like in menu items, buttons, or navigation bars.
Important Note
1. Environment (Where you can use it)
useNavigate() works only inside a Router
That means your app must be wrapped like this:
<BrowserRouter>
<App />
</BrowserRouter>
If you don’t do this → it will give an error
2. useNavigate vs
Both are used for navigation, but in different situations:
Use (best for normal clicking)
Go to Home
Good for:
Navigation menus
Buttons/links users click
Why better?
More accessible
Works like normal HTML links
Use useNavigate() (for logic-based navigation)
navigate("/home");
Use when:
After login → go to dashboard
After form submit → go to success page
After timeout → redirect
3. Class Components limitation
useNavigate() is a hook
Hooks cannot be used in class components
What to do instead?
Option 1: Use
Option 2: Wrap with HOC (advanced way)
Convert navigation into props using a wrapper
SUMMARY
useNavigate()
Works only inside Router
Best for user clicking navigation
useNavigate()
Best for automatic / logic-based navigation
Not usable in class components
Use instead in class components
Questions
1.What is the main purpose of the useNavigate() hook in React Router v6?
Answer:
To navigate between routes programmatically
2.Which hook does useNavigate() replace from older React Router versions?
Answer:
useHistory()
3.How can you prevent users from returning to the previous page when navigating using useNavigate()?
Answer:
Using navigate('/path', { replace: true })
4.Which of the following is a correct way to navigate one step back using useNavigate()?
Answer:
navigate(-1)
Top comments (0)