I want to force a page reload (even when navigating using the back button) because in Safari browsers, Safari will load a cached version of the page which is not what we want.
Using React Hooks, I can do this in useEffect
.
function MyComponent() {
useEffect(() => {
if (typeof window != 'undefined') {
window.onpageshow = event => {
if (event.persisted) {
window.location.reload()
}
}
}
}, [])
return (<div>My Page Content</div>)
}
My question is: when doing this, will the reload repeatedly get called because a reload will trigger a re-render and re-mounting of the component, which in turn will call useEffect, which will then call reload and then get into this infinite cycle?
Another way to do this is to mimic a React class constructor
:
function MyComponent() {
const [reloadHasRun, setReloadHasRun] = useState(false)
const forceReload = () => {
if (typeof window !== 'undefined') {
window.onpageshow = event => {
if (event.persisted) {
window.location.reload()
}
}
}
setReloadHasRun(true)
}
if (!reloadHasRun)
forceReload()
return (<div>My Page Content</div>)
}
But again, I have this same question. Does the forcing of the reload get me into this situation where the component is continually being re-rendered, re-mounted, and the reload being called over and over again?
Ultimately, what I want to have happen is when the back button is clicked on Safari, that the previous page is reloaded and not just pulled from cache.