Skip to content

Instantly share code, notes, and snippets.

@isocroft
Last active March 3, 2025 18:39
Show Gist options
  • Select an option

  • Save isocroft/45c23b6b4cf0d463fecdc7dfe65f237d to your computer and use it in GitHub Desktop.

Select an option

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