Repository navigation
Why does useRouter from next/router throw an error in Next.js 13+ app directory? #92073
Replies: 2 comments 1 reply
|
For the App Router, import from 'use client'
import { useRouter } from 'next/navigation'
export default function Component() {
const router = useRouter()
// router.push(), router.replace(), router.back(), router.refresh(), router.prefetch()
}Two things worth knowing since the API isn't identical to the Pages Router version: If you ever need one component that works in both |
|
Your tutorial was written for the Pages Router ( Fix: change the import and mark the file as a Client Component: 'use client'
import { useRouter, usePathname, useSearchParams, useParams } from 'next/navigation'
export default function MyButton() {
const router = useRouter()
return <button onClick={() => router.push('/dashboard')}>Go</button>
}Quick mapping from the old API to the new one:
Two common gotchas:
Docs: https://nextjs.org/docs/app/api-reference/functions/use-router#migrating-from-nextrouter |
Uh oh!
There was an error while loading. Please reload this page.
Summary
I was following a tutorial and it told me to import useRouter from next/router but I'm getting this error:
Error: invariant expected app router to be mounted
I'm using the app directory. What am I doing wrong?
Additional information
No response
Example
No response
All reactions