next-router-prefetch is a custom hook that wraps useRouter.Apply prefetch to links that do not use the Link component.
MIT License
✋ This version uses Next.js 11. For earlier versions, please use this one.
next-router-prefetch
is a custom hook that wraps useRouter.
Apply prefetch to links that do not use the Link component.
Usually,
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
!
yarn add @dc7290/[email protected] # npm i @dc7290/[email protected]
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.
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 (
<div ref={prefetchTarget} onClick={handleRouterPush}>
Link to 'foo' page.
</div>
);
};
// Use with observe = false
const BarComponent = () => {
const { handleRouterPush } = useRouterPrefetch("/bar", false);
useEffect(() => {
if (login) {
handleRouterPush();
}
});
return <div>Example login page.</div>;
};
import React, { useEffect } from "react";
import { useRouterPrefetch } from "@dc7290/next-router-prefetch";
const FooComponent: React.VFC = () => {
const { handleRouterPush, prefetchTarget } =
useRouterPrefetch<HTMLDivElement>("/foo");
// You can also give it to them in the following ways
// const { handleRouterPush, prefetchTarget } = useRouterPrefetch<HTMLDivElement>({
// pathname: "/posts/[postId]";
// query: {
// postId: 1;
// };
// hash: "title";
// });
return (
<div ref={prefetchTarget} onClick={handleRouterPush}>
Link to 'foo' page.
</div>
);
};
// Use with observe = false
const BarComponent: React.VFC = () => {
const { handleRouterPush } = useRouterPrefetch("/bar", false);
useEffect(() => {
if (login) {
handleRouterPush();
}
});
return <div>Example login page.</div>;
};
value | description |
---|---|
string or UrlObject | Specifies the transition destination.It takes on the same type as when passed to router.push(). |
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. |
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) |
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 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. |
Here are some useful ways to use it.
import { pagesPath } from "~/utils/$path";
// ~~~~ abbreviation
const { handleRouterPush, prefetchTarget } = useRouterPrefetch<HTMLElement>(
pagesPath.posts._postId(props.url).$url()
);
// ~~~~ abbreviation
It is also possible to work with 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!
dc7290 [email protected]
"next-router-prefetch" is under MIT license.