npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dc7290/next-router-prefetch

v4.0.0

Published

This provides a custom hook that contains 'next/router'.

Downloads

69

Readme

next-router-prefetch

npm version license downloads

✋ 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.

日本語

Features

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!

Installation

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

Usage

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

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>;
};

Example of use in TypeScript

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>;
};

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) | | 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 trueshallow: Update the path of the current page without rerunning getStaticProps, getServerSideProps or getInitialProps. Defaults to falselocale: 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

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!

Author

dc7290 [email protected]

License

"next-router-prefetch" is under MIT license.