DEV Community

Cover image for Differences Between useRouter and useParams
Dhruv Pankaj Patel
Dhruv Pankaj Patel

Posted on

Differences Between useRouter and useParams

Understanding the distinction between useParams and useRouter is crucial for efficient routing in React-based applications. These hooks are used for accessing URL parameters, but they serve different purposes and are used in different contexts.

useParams (React Router)

useParams is a hook in React Router, primarily used to access dynamic segments of the URL.

  • Example:
import { useParams } from 'react-router-dom';

function UserProfile() {
  const { userId } = useParams();

  return <div>User ID: {userId}</div>;
}

Enter fullscreen mode Exit fullscreen mode

In this example, for a route configured as /user/:userId, useParams allows us to extract userId from the URL.

useRouter in Next.js

In Next.js, useRouter is a hook from the "next/router" (pages router) module, providing access to the Next.js router object. It offers extensive functionalities, including access to query parameters, programmatic navigation, and more.

  • Example:
import { useRouter } from 'next/router';

function ProductPage() {
  const router = useRouter();
  const { id, color } = router.query;

  return (
    <div>
      <p>Product ID: {id}</p>
      <p>Color: {color}</p>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, useRouter is used to access both dynamic route parameters (id) and query parameters (color) for a route like /products/[id]?color=blue.

If you're using the app directory in Next.js, please import the useRouter hook from "next/navigation" like this import { useRouter } from "next/navigation";

Context

  • useParams is used in React Router.
  • useRouter is specific to Next.js.

Functionality:

  • useParams only accesses dynamic route parameters.
  • useRouter accesses both dynamic route parameters and query parameters. It also provides additional routing functionalities like navigation and event handling.

Usage:

  • useParams is simpler and more focused.
  • useRouter is more comprehensive and versatile for handling various aspects of routing in Next.js applications.

Random senior dev:

Understanding these differences helps in making informed decisions about routing strategies in your React or Next.js projects.

Top comments (0)