Skip to content

Instantly share code, notes, and snippets.

@hnordt
Created January 27, 2022 17:32
Show Gist options
  • Save hnordt/0c6a37feb99d800f15d0cf94681e6db8 to your computer and use it in GitHub Desktop.
Save hnordt/0c6a37feb99d800f15d0cf94681e6db8 to your computer and use it in GitHub Desktop.
import React from "react"
import { useLocation, useNavigate } from "remix"
export default function useWindowFocusRefetching() {
const location = useLocation()
const navigate = useNavigate()
const pathnameRef = React.useRef(location.pathname)
React.useEffect(() => {
pathnameRef.current = location.pathname
})
React.useEffect(() => {
function refetch() {
navigate(pathnameRef.current, {
state: {
windowFocusedAt: new Date().toISOString(),
},
replace: true,
})
}
window.addEventListener("focus", refetch)
return () => window.removeEventListener("focus", refetch)
}, [navigate])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment