Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/dc7290/next-router-prefetch

next-router-prefetch is a custom hook that wraps useRouter.Apply prefetch to links that do not use the Link component.
https://github.com/dc7290/next-router-prefetch

nextjs react react-hooks typescript

Last synced: about 1 month ago
JSON representation

next-router-prefetch is a custom hook that wraps useRouter.Apply prefetch to links that do not use the Link component.

Awesome Lists containing this project

README

        

# next-router-prefetch

[![npm version](https://img.shields.io/npm/v/@dc7290/next-router-prefetch)](https://www.npmjs.com/package/@dc7290/next-router-prefetch) [![license](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/cyrilwanner/@dc7290/next-router-prefetch/blob/master/LICENSE) [![downloads](https://img.shields.io/npm/dt/@dc7290/next-router-prefetch)](https://www.npmjs.com/package/@dc7290/next-router-prefetch)

✋ This version uses Next.js 11.
For earlier versions, please use this [one](https://www.npmjs.com/package/@dc7290/next-router-prefetch/v/2.2.2).

---

`next-router-prefetch` is a custom hook that wraps useRouter.

Apply prefetch to links that do not use the Link component.

[日本語](https://github.com/dc7290/next-router-prefetch/blob/main/docs/README-ja.md)

## Features

Usually,

```typescript
const router = useRouter();
router.push("/about");
```

If you try to transition pages in this way, it will take some time to load before you can transition.

If this is a page transition with the `next/link`(Link) component, it will automatically prefetch the link destination when the link enters the viewport.
(Unless you have set `prefetch={false}`.)

However, if you use `router.push`, the page will not be moved immediately because automatic prefetch is not performed.


The solution to this is `next-router-prefetch`!

## Installation

```bash
yarn add @dc7290/[email protected] # npm i @dc7290/[email protected]
```

## Usage

```js
useRouterPrefetch(url, observe, nextRouterOptions);
```

Use the first argument to enter the link destination.

This link can be the same as the one used in `router.push`, so it can be a `UrlObject` as well as a string.

The `UrlObject` received internally is converted to a string so that it can be applied to `router.prefetch`, so there is no need to pass a string for prefetch.


Running `useRouterPrefetch()` will return `handleRouterPush` and (if observe is `true`) `prefetchTarget`.


`handleRouterPush`, as the name suggests, is a function that transitions to the passed link destination.

Use this in the event you want to trigger, or in useEffect, etc.


`prefetchTarget` is a ref object that is supposed to be observed by `IntersectionObserver`.

Set this to the ref of the element you want prefetched when it enters the viewport.

#### Example of use in JavaScript

```js
import React, { useEffect } from "react";
import { useRouterPrefetch } from "@dc7290/next-router-prefetch";

const FooComponent = () => {
const { handleRouterPush, prefetchTarget } = useRouterPrefetch("/foo");
// You can also give it to them in the following ways
// const { handleRouterPush, prefetchTarget } = useRouterPrefetch({
// pathname: "/posts/[postId]";
// query: {
// postId: 1;
// };
// hash: "title";
// });

return (


Link to 'foo' page.

);
};

// Use with observe = false
const BarComponent = () => {
const { handleRouterPush } = useRouterPrefetch("/bar", false);
useEffect(() => {
if (login) {
handleRouterPush();
}
});

return

Example login page.
;
};
```

#### Example of use in TypeScript

```ts
import React, { useEffect } from "react";
import { useRouterPrefetch } from "@dc7290/next-router-prefetch";

const FooComponent: React.VFC = () => {
const { handleRouterPush, prefetchTarget } =
useRouterPrefetch("/foo");
// You can also give it to them in the following ways
// const { handleRouterPush, prefetchTarget } = useRouterPrefetch({
// pathname: "/posts/[postId]";
// query: {
// postId: 1;
// };
// hash: "title";
// });

return (


Link to 'foo' page.

);
};

// Use with observe = false
const BarComponent: React.VFC = () => {
const { handleRouterPush } = useRouterPrefetch("/bar", false);
useEffect(() => {
if (login) {
handleRouterPush();
}
});

return

Example login page.
;
};
```

## Options

#### url

| value | description |
| ------------------- | --------------------------------------------------------------------------------------------------- |
| string or UrlObject | Specifies the transition destination.
It takes on the same type as when passed to router.push(). |

#### observe

| value | description |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| boolean | Use `IntersectionObserver` to decide whether to prefetch or not.
The default is true, and if set to `false` it will prefetch immediately after rendering. |

#### nextRouterOptions

This is the same as the default optins for router.push.

| key | value | description |
| --------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| intersectionObserverOptions | IntersectionObserverInit | Specify the options to be passed to IntersectionObserver when observe is set to true.[reference(MDN)](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver#parameters) |
| as | string or UrlObject | Optional decorator for the path that will be shown in the browser URL bar.
Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. |
| options | object | Optional object with the following configuration options:
scroll: Scroll to the top of the page after a navigation. Defaults to `true`
shallow: Update the path of the current page without rerunning `getStaticProps`, `getServerSideProps` or `getInitialProps`. Defaults to `false`
locale: The active `locale` is automatically prepended. locale allows for providing a different locale. When `false` `href` has to include the locale as the default behavior is disabled. |

## Tips

Here are some useful ways to use it.

#### Linking with pathpida

```typescript
import { pagesPath } from "~/utils/$path";

// ~~~~ abbreviation

const { handleRouterPush, prefetchTarget } = useRouterPrefetch(
pagesPath.posts._postId(props.url).$url()
);

// ~~~~ abbreviation
```

It is also possible to work with [pathpida](https://github.com/aspida/pathpida), a library that makes links type-safe, in this way.
And you don't need to pass `pagesPath.posts._postId(props.url)`. You don't even need to pass `$url().pathname` as a string to make pathpida even more useful!

## Author

dc7290
[email protected]

## License

"next-router-prefetch" is under [MIT license](https://en.wikipedia.org/wiki/MIT_License).