useRouter hook
Next.js provides a useRouter hook to access the router object and provides various methods to perform a operations. If you have selected Pages Router, while creating app then you have to import useRouter hook from next/router and you can access the router object and use it’s methods.
If you have selected App Router, while creating app then you have to import useRouter hook from next/navigation and to access different information such as pathname, query then you have to use usePathname, useSearchParams to get those values.
Here, we are using App Router.
Syntax:
'use client'
import { useRouter } from 'next/navigation'
const router = useRouter()
router.push('/path')
Example:
//File path : ./src/app/page.js
'use client'
import { useRouter } from "next/navigation";
export default function Home() {
const router = useRouter()
return (
<>
<h1>Home Page</h1>
<li onClick={()=>router.push('/about')}>About Page</li>
</>
);
}
//File path : ./src/app/about/page.js
'use client';
import { useRouter } from "next/navigation";
export default function Page() {
const router = useRouter();
return (
<>
<h1>About page</h1>
<li onClick={() => router.push('/')}>Home Page</li>
</>
)
}
Output:
Difference between NextJS Link vs useRouter in Navigating
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is navigation. Navigation is crucial for providing users with seamless browsing experiences.
Next.js provides two primary methods Link component and the useRouter hook for navigation. In this article, we will learn about the difference between the Link component and useRouter hook.
Table of Content
- Link Component
- useRouter hook
- Differences between Link and useRouter
Contact Us