Open In App

useRouter in Next JS

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Next.js is a React framework that is used to build full-stack web applications. It is used both for front-end as well and back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is useRouter hook that is part of the Next.js routing system.

In this article, we will learn about how to use useRouter hook. The useRouter hook allows you to access the Next.js router object and obtain information about the current route, query parameters, and other route-related details.

Note: We’ll use the Pages Router(not using App Router), so if you are using App Router then properties like pathname, query, etc, and some methods will not work directly so you need to use specific hooks like usePathname, useSearchParams to get this values and you need import useRouter hook module from next/navigation.

Syntax

The useRouter hook is imported from the next/router module in Next.js applications.

import { useRouter } from 'next/router ';

function MyComponent() {

//Main Syntax
const router = useRouter();

// Accessing route information using router object
console.log(router.pathname); // Current route
console.log(router.query); // Query parameters

return (
// Your component JSX
);
}

The hook provides access to various properties and methods of the Next.js router object.

useRouter Properties:

  • router.pathname: It is a string representing the path of the current route. (ex. “/blog/post-1”)
  • router.query: It is a object containing the query parameters of the current route. (ex. { id: ‘1’, category: ‘tech’ } )
  • router.asPath: It is a string representing the actual path (including the query) shown in the browser. (ex. ‘/blog/post-1?id=1&category=tech’)
  • router.route: It is a string representing the matched route pattern for the current route. (ex. ‘/blog/[slug]’ )
  • router.isFallback: It is a Boolean value indicating whether the page is in fallback mode (used for dynamic routes with getStaticPaths and getStaticProps).

useRouter Methods:

  • router.push(url, as, options): It is used to Navigates to a new page.
  • router.replace(url, as, options): It is used to replaces the current page with a new one without adding an entry to the browser’s history.
  • router.reload(): It reloads the current page.
  • router.back(): It is used to navigates back in the browser’s history.

Steps to Create Next.js Application

Step 1: Create a Next.js application using the following command.

npx create-next-app@latest gfg

Step 2: It will ask you some questions, so choose as the following.

Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... No (We are using Pages Router)
√ Would you like to customize the default import alias (@/*)? ... Yes

Step 3: After creating your project folder i.e. gfg, move to it using the following command.

cd gfg

Project Structure:

useRouter-project-structure

Example: The below example demonstrates the use of useRouter hook.

Note: Remove the included css file from _app.js file

Step 1: Add this following code inside index.js file

Javascript




//File path: src/pages/index.js
import { useRouter } from "next/router";
 
export default function Home() {
 
  // Using the useRouter hook
  const router = useRouter();
 
  return (
    <>
      <h1>GeeksForGeeks | useRouter Hook</h1>
      <p>Current Pathname: {router.pathname}</p>
      <p>Query Parameters: {JSON.stringify(router.query)}</p>
      <button onClick={ () => router.push('/about/?name=GeeksForGeeks') }>
          Click here to go to About Page with Query
      </button>
    </>
  );
}


Step 2: Create about.js file and add the following code in the file:

Javascript




//File path: src/pages/about.js
import { useRouter } from 'next/router';
 
function Page() {
  // Using the useRouter hook
  const router = useRouter();
 
  return (
    <>
      <h1>Click the below BACK button to go back to previous page</h1>
      <p>Current Pathname: {router.pathname}</p>
      <p>Query Parameters: {JSON.stringify(router.query)}</p>
      <button onClick={() => router.back()}>BACK</button>
    </>
  );
}
 
export default Page;


To run the Application open the terminal in the project folder and enter the following command:

npm run dev

Output:

useRouter-output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads