Is there any way I can detect page reload on react app. I only want to detect when the page is reloaded when user clicks the reload button or shortcut keys to reload the page not when the page changes without reload when using react router.
I tried using beforeunload but it also detects page changes that react router does.
useEffect(() => {
window.addEventListener("beforeunload", alertUser);
return () => {
window.removeEventListener("beforeunload", alertUser);
};
}, []);
2
Answers
I think the best way to do this is to use
useEffect(() => ...)
in your root component (most likely something calledApp.tsx
orApp.jsx
) this will only fire when theReact
application is initialized. Furthermore if you want to only let it run some code on reload you can pass a query paramenter like?reload=true
or something in the URL.You can use the Performance Navigation Timing interface with React/React-Router-Dom to resolve that. Please see my approach below and read more about the Performance Navigation Timing interface.