0

I've been stuck on this for hours, how can I detect a page refresh and reroute the user to a specific path? /error for example

I'm using useNavigate for rerouting, it works but I dont know how to properly listen for a page refresh

ashketchup
  • 21
  • 5

1 Answers1

0

here is what you need in this example. In fact, with this method you can detect if that page has refreshed or reloaded, so you can use the useEffect and performance.

You use the method navigate to be able to navigate the pages. Don't forget if you have any state you can include it in the dependency array of the useEffect().

import React, { useEffect } from "react";

export default function NavigationDectector() {
  const { navigate} = useNavigate();
  useEffect(() => {
    if (performance.navigation.type === 1) {
      console.log("This page is reloaded");
      // here you can navigate 
    } else {
      console.log("This page is not reloaded");
    }
    // if you have any state which you depend on the reload put it in the 
    array of the use effect
  },[]);

  return <div></div>;
}

I hope this can helps you

Anas Ben Yaiche
  • 225
  • 3
  • 7