I’m migrating my Next.js project from version 12 to 14 and encountered an issue with a loading component that used to work perfectly. Now, I’m getting the following error:
Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted
srccomponentsLoading.tsx (10:26) @ useRouter
This is the relevant code for my Loading
component, which listens to route changes:
path: src/component/Loading.tsx
'use client'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'
import styles from './Loading.module.scss'
const Loading = () => {
const [loading, setLoading] = useState(false)
const router = useRouter()
useEffect(() => {
const handleStart = () => setLoading(true)
const handleComplete = () => setTimeout(() => setLoading(false), 1000)
router.events.on('routeChangeStart', handleStart)
router.events.on('routeChangeError', handleComplete)
router.events.on('routeChangeComplete', handleComplete)
return () => {
router.events.off('routeChangeStart', handleStart)
router.events.off('routeChangeError', handleComplete)
router.events.off('routeChangeComplete', handleComplete)
}
})
return loading && <div className={styles.loading} />
}
export default Loading
I have the Loading
component inside the RootLayout
like this:
path: src/app/layout.tsx
import Loading from '@/components/Loading'
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang='en'>
<body suppressHydrationWarning>
<Loading />
{children}
</body>
</html>
)
}
In Next.js 12, this setup worked fine, but after upgrading to version 14, I kept getting the error mentioned above.
I suspect it has something to do with the app router and how Next.js 14 handles routing differently, but I haven’t found a clear explanation or solution.
2
You do not need to use your custom logic by creating Loading component.
Next.js 14 App router provides loading.(tsx/jsx/js)
file. You can create the file in the same level of your root layout (or whatever layout you want to wrap with the loading).
Next.js article on Loading UI