Unverified Commit 1f324c72 authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

[Docs] Add documentation for Router.prefetch (#12333)

parent eb9d10fa
......@@ -154,6 +154,59 @@ Router.replace('/home')
The API for `Router.replace` is exactly the same as that used for [`Router.push`](#router.push).
### Router.prefetch
Prefetch pages for faster client-side transitions. This method is only useful for navigations without [`next/link`](/docs/api-reference/next/link.md), as `next/link` takes care of prefetching pages automatically.
> This is a production only feature. Next.js doesn't prefetch pages on development.
```jsx
import Router from 'next/router'
Router.prefetch(url, as)
```
- `url` - The path to a `page` inside the `pages` directory
- `as` - Optional decorator for `url`, used to prefetch [dynamic routes](/docs/routing/dynamic-routes). Defaults to `url`
#### Usage
Let's say you have a login page, and after a login, you redirect the user to the dashboard. For that case, we can prefetch the dashboard to make a faster transition, like in the following example:
```jsx
import { useCallback, useEffect } from 'react'
import Router from 'next/router'
export default function Login() {
const handleSubmit = useCallback(e => {
e.preventDefault()
fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
/* Form data */
}),
}).then(res => {
// Do a fast client-side transition to the already prefetched dashbaord page
if (res.ok) Router.push('/dashboard')
})
}, [])
useEffect(() => {
// Prefetch the dashboard page as the user will go there after the login
Router.prefetch('/dashboard')
}, [])
return (
<form onSubmit={handleSubmit}>
{/* Form fields */}
<button type="submit">Login</button>
</form>
)
}
```
### Router.beforePopState
In some cases (for example, if using a [Custom Server](/docs/advanced-features/custom-server.md)), you may wish to listen to [popstate](https://developer.mozilla.org/en-US/docs/Web/Events/popstate) and do something before the router acts on it.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment