Created
March 20, 2024 21:44
-
-
Save kinngh/0729ed597f3a94f69ed25e3ba1896d86 to your computer and use it in GitHub Desktop.
Prefetch Next.js routes to speed up navigation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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