Last active
March 3, 2025 18:39
-
-
Save isocroft/45c23b6b4cf0d463fecdc7dfe65f237d to your computer and use it in GitHub Desktop.
A hook for auto/manual refresh of a route in NextJS v13+ (React v17.0.x - v19.0.x) app router software
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/navigation"; | |
| import { useEffect, useTransition } from "react"; | |
| const useNextJSAppRouteRefresh = ( | |
| { intervalDurationInMilliseconds = 0, autoRefreshOnMount = false }: { | |
| intervalDurationInMilliseconds: number, | |
| autoRefreshOnMount: boolean | |
| } | |
| ) => { | |
| const [isPending, startTransition] = useTransition(); | |
| const router = useRouter(); | |
| useEffect(() => { | |
| if (!autoRefreshOnMount) return; | |
| let timeout: NodeJS.Timeout; | |
| const refresh = () => { | |
| startTransition(() => { | |
| router.refresh(); | |
| }); | |
| timeout = setTimeout(refresh, intervalDurationInMilliseconds); | |
| }; | |
| const handleVisibilityChange = () => { | |
| if (document.hidden) { | |
| clearTimeout(timeout); | |
| } else { | |
| refresh(); | |
| } | |
| }; | |
| window.addEventListener("visibilitychange", handleVisibilityChange); | |
| refresh(); | |
| return () => { | |
| clearTimeout(timeout); | |
| window.removeEventListener("visibilitychange", handleVisibilityChange); | |
| }; | |
| }, [intervalDurationInMilliseconds, router, autoRefreshOnMount]); | |
| return { | |
| isPending, | |
| refreshNow () { | |
| if (!isPending && !autoRefreshOnMount) { | |
| startTransition(() => { | |
| router.refresh(); | |
| }); | |
| } | |
| } | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment