Next.js - useRouter Function



In Next.js useRouter function is used to access router object in Next.js. In this chapter we will learn what is useRouter function, how to use it, syntax and example usage of useRouter method.

Next.js useRouter Method

The useRouter method in Next.js is used to interact with router object by accessing routing-related data and methods. The router object can access the current route, pathname, and query parameters. Also this object can be used to programmatically navigate between different routes in an application.

Syntax

Following shows basic usage syntax of useRouter function.

// Import the library
import { useRouter } from 'next/router';

const MyComponent = () => {
    // Receive the router object
    const router = useRouter();

    // Display the name of current route
    return <div>Current Route: {router.pathname}</div>;
};
  • Arguments: The useRouter method doesn't take any arguments.
  • Return Type: The useRouter method return a router object which can interact with the Next.js router and access routing-related data and methods.

Example of Using useRouter

In the example code below, we implemented a product ordering feature to the product page we created in the previous chapters. On clicking the button, user will get a confirmation of the order and redirect them to home page using 'useRoute' hook.

"use client"; 

import { useRouter } from "next/navigation";
import { PageProps } from "next/dist/shared/lib/router/utils/page-props";

export default function ProductPage({ params }: PageProps) {
    const router = useRouter();

    const handleClick = () =>{
        alert("Order Placed...");

        // Navigate to home page after placing order
        router.push("/");
    };
    return (
        <div>
            <h1>Product {params.id}</h1>
            <p>This is the product page for item {params.id}</p>
            <button onClick={handleClick}>Order Item</button>
        </div>
    );
}

Output

In the output, after placing order user is getting redirected to home page.

next.js-navigating-dynamically
Advertisements