Skip to content

Instantly share code, notes, and snippets.

@kinngh
Created March 20, 2024 21:44
Show Gist options
  • Save kinngh/0729ed597f3a94f69ed25e3ba1896d86 to your computer and use it in GitHub Desktop.
Save kinngh/0729ed597f3a94f69ed25e3ba1896d86 to your computer and use it in GitHub Desktop.
Prefetch Next.js routes to speed up navigation
import { useRouter } from "next/router";
import { useEffect } from "react";
/**
* Prefetch routes to make navigation between pages faster
*
* @param {Array<string>} paths An array of paths (URLs) to prefetch.
*/
const usePrefetchRoutes = (paths) => {
const router = useRouter();
useEffect(() => {
if (paths && paths.length > 0) {
paths.forEach((path) => {
router.prefetch(path);
});
}
}, [paths, router]);
};
export default usePrefetchRoutes;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment