useRouter
This hook is only available in NextJs (App Router)
The useRouter hook gives you programmatic control over routing in your NextJs application. With this hook, you can:
- Navigate between pages.
- Go back in history.
- Refresh the current route.
- Replace the URL without reload.
- Get the current path (using usePathname)
When you are using the App router, import useRouter as follows:
import { useRouter } from "next/navigation";
When you are using the pages router, import useRouter as follows:
import { useRouter } from "next/router";
Syntax
const router = useRouter();
Once you do this, you get access to the following functions:
Function | Description |
---|---|
router.push(url) | Navigate to a new URL (adds to the history stack). Takes in a url string of the new page you want to navigate to. |
router.replace(url) | Navigate to the new page without adding to the history stack. Takes in a url string. |
router.back() | Go back to the previous page in history stack. Does not take any parameter. |
router.refresh() | Refresh the current page. Does not take in any parameter. |
Examples
Navigate after form submission
If you wanted to navigate to a new page after a user signs up, you could do something like this:
"use client";
import { useRouter } from "next/navigation";
function SignupForm() {
const router = useRouter();
function handleSubmit(e) {
e.preventDefault();
// handle logic...
router.push("/dashboard"); // go to dashboard after signup
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Name" />
<button type="submit">Sign Up</button>
</form>
);
}
Notice the use client
directive at the top of the file. Since NextJs is
server-rendered by default, you cannot use any hooks in it because hooks are
client-side only. Therefore, you need to tell NextJs that this is a client
component by adding the use client
directive.
Going back to the previous page
Go back to the previous page when you click the button.
"use client";
import { useRouter } from "next/navigation";
export default function GoBackButton() {
const router = useRouter();
return <button onClick={() => router.back()}>← Go Back</button>;
}
This is basically like the browser’s Back button.
Replace the URL
router.replace
works almost like router.push
. The difference is that when you replace the URL, you cannot navigate back to the previous page. But with push, you can navigate back.
"use client";
import { useRouter } from "next/navigation";
function SignupForm() {
const router = useRouter();
function handleSubmit(e) {
e.preventDefault();
// handle logic...
router.replace("/dashboard"); // go to the dashboard after signup
}
return (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="Name" />
<button type="submit">Sign Up</button>
</form>
);
}