Solution

To check if the page is refreshed in react js, use the window.performance.navigation method if it will contain reload navigation entries it means the page is refreshed.

window.performance.navigation

The navigation read-only property of the Window interface returns the current window’s associated Navigation object.

Snippet

In this snippet, we will note important parts checking reloaded pages.

const pageAccessedByReload = (
  (window.performance.navigation && window.performance.navigation.type === 1) ||
    window.performance
      .getEntriesByType('navigation')
      .map((nav) => nav.type)
      .includes('reload')
);

console.log(pageAccessedByReload) // true for realoded pages

Example

In this example, we will check page is refreshed or not and store the value in the state and then show the state value on the page.

Let’s start coding…

import React, { useState, useEffect } from "react";
export default function App() {
  const [isReloaded, setIsReloaded] = useState(false);

  useEffect(() => {
    const pageAccessedByReload = (
      (window.performance.navigation && window.performance.navigation.type === 1) ||
        window.performance
          .getEntriesByType('navigation')
          .map((nav) => nav.type)
          .includes('reload')
    );

    setIsReloaded(pageAccessedByReload);

  }, []);


  return (
    <div className="App">
      <h1>{`Is Page Refreshed?`}</h1>
      <p>{isReloaded}</p>
    </div>
  );
}

Output

check, refreshed

codesandbox