Next.js Replace Next Router

verified codemod icon

This automation allows you to migrate the useRouter hook to the new useRouter hook imported from next/navigation.

Next.js
ts-morph
Estimated time saving
5 minutes/occurrence
Change mode
Autonomous
Applicability criteria

Next.js version is greater or equal to 13.4.

Made by
Codemod.com
Codemod.com

Usage →

Codemod CLI:

intalling vs code extension tooltip icon
codemod next/13/replace-next-router
copy CLI command icon

Codemod VS Code extension:

intalling vs code extension tooltip icon
vs code logo
Run in VS Code

Description

Since Next.js 13.4, you can use the following hooks from the next/navigation module:

  • useRouter,
  • useSearchParams,
  • usePathname,
  • useParams.

These hooks replace the functionality available in the useRouter hook in the next/hook module, however, the behavior is distinct.

This codemod allows you to migrate the useRouter hook to the new useRouter hook imported from next/navigation. This includes all usages of the useRouter hook which may be replaced with useSearchParams and usePathname.

Example

Before

import { useRouter } from 'next/router';

function Component() {
	const { query } = useRouter();
	const { a, b, c } = query;
}

After

import { useParams, useSearchParams } from 'next/navigation';
import { useCallback } from 'react';

function Component() {
	const params = useParams();
	const searchParams = useSearchParams();
	const getParam = useCallback(
		(p: string) => params?.[p] ?? searchParams?.get(p),
		[params, searchParams],
	);

	const a = getParam('a');
	const b = getParam('b');
	const c = getParam('c');
}