0

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 Answers2

0

I think the best way to do this is to use useEffect(() => ...) in your root component (most likely something called App.tsx or App.jsx) this will only fire when the React 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.

Lars Vonk
  • 623
  • 5
  • 13
  • Thank you. This works. But how do I detect page reload inside a component. What I am trying to achieve is conditionally render a component when page gets reloaded. – Ananta Rai Mar 07 '23 at 10:42
  • 1
    I think you need to pass down a `prop` from the root component to the component you are talking about – Lars Vonk Mar 07 '23 at 10:47
  • I found another way to get around this issue. Thanks for your input. – Ananta Rai Mar 07 '23 at 12:07
  • What way did you find? Just wondering maybe it is a cleaner way than i am doing it in my projects? :-) – Lars Vonk Mar 07 '23 at 12:12
  • The solution I found is specific to the application I am working on. So the setup is I am using api that is built in laravel and react on frontend. I am newbie in react and was having issues conditionally rendering a component when the page reloads. I ended moving the logic to my blade file (Templating engine in a Laravel) where the react app gets rendered. – Ananta Rai Mar 07 '23 at 13:42
0

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.

import React from "react";
import { Navigate } from "react-router-dom";

export default function Navigator = () => {
  const {navigate} = useNavigate();
  const navigationCondition = (window.performance.navigation && 
                            window.performance.navigation.type === 1) 

  React.useEffect(() => {
    if (navigationCondition) {
      console.log("Reload detected");
      <Navigate to="/where-you-need-to-go" replace={true} />
    } else {
      console.log("No reload");
    }
  },[]);

  return <></>;
}
Evan
  • 35
  • 4
  • This answer doesn't make much sense, and I don't believe it addresses the issue OP is asking about of a page reload. – Drew Reese Mar 08 '23 at 06:56