update-on-return.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use client";
  2. import { useEffect } from "react";
  3. /** How long a tab has to be away before it asks whether it is out of date. */
  4. const AWAY = 60_000;
  5. /**
  6. * Reloads a tab that comes back after a new deploy, so a page left open on a
  7. * phone for days never shows bugs that have since been fixed. It reloads at
  8. * most once per build.
  9. */
  10. export function UpdateOnReturn() {
  11. useEffect(() => {
  12. let hiddenAt = 0;
  13. const check = async () => {
  14. try {
  15. const res = await fetch("/api/version", { cache: "no-store" });
  16. const { build } = (await res.json()) as { build?: string };
  17. if (!build || build === process.env.SITE_BUILD) return;
  18. if (sessionStorage.getItem("reloaded-for") === build) return;
  19. sessionStorage.setItem("reloaded-for", build);
  20. location.reload();
  21. } catch {}
  22. };
  23. const onVisibility = () => {
  24. if (document.hidden) hiddenAt = Date.now();
  25. else if (hiddenAt && Date.now() - hiddenAt > AWAY) check();
  26. };
  27. // Restored from the back/forward cache: as good as a tab coming back.
  28. const onShow = (e: PageTransitionEvent) => {
  29. if (e.persisted) check();
  30. };
  31. document.addEventListener("visibilitychange", onVisibility);
  32. window.addEventListener("pageshow", onShow);
  33. return () => {
  34. document.removeEventListener("visibilitychange", onVisibility);
  35. window.removeEventListener("pageshow", onShow);
  36. };
  37. }, []);
  38. return null;
  39. }