Skip to content

Commit

Permalink
docs: enhanced next-router-not-mounted error page
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattjoh committed Nov 18, 2022
1 parent f91e11e commit 4dc8cfc
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions errors/next-router-not-mounted.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
# NextRouter was not mounted
# `NextRouter` was not mounted

#### Why This Error Occurred

A component used `useRouter` outside a Next.js application, or was rendered outside one. This can happen when doing unit testing on components that use the `useRouter` hook as they are not configured with Next.js' contexts.
A component that used `useRouter` was rendered outside the `pages/` directory. This can happen when migrating to the `app/` directory. Situations where you also render components outside a Next.js application (like in unit tests) can also trigger this error.

#### Possible Ways to Fix It

If used in a test, mock out the router by mocking the `next/router`'s `useRouter()` hook.
If you're migrating components over from `pages/` to `app/`, you can take advantage of the compatibility hooks that are designed to be used in transition when components are shared between `pages/` and `app/`. Instead of writing:

```tsx
import { useRouter } from 'next/router'
```

You would write:

```tsx
import { useRouter } from 'next/compat/router'
```

When the router context is not available, this hook will return `null` instead of throwing an error. Developers should migrate over to the new router hook available at `next/navigation` which is fully supported in `app/`.

If you're unit testing components that rely on these hooks, you should mock the the `next/router`'s `useRouter()` hook instead.

### Useful Links

- [next-router-mock](https://www.npmjs.com/package/next-router-mock)
- [`next-router-mock`](https://www.npmjs.com/package/next-router-mock)
- [`useRouter` from `next/navigation`](https://beta.nextjs.org/docs/api-reference/use-router)

0 comments on commit 4dc8cfc

Please sign in to comment.