Sometimes, we want to detect page refresh by pressing F5 in a React component.
In this article, we’ll look at how to detect page refresh by pressing F5 in a React component.
Detect Page Refresh by Pressing F5 in a React Component
To detect page refresh by pressing F5 in a React component, we can use the performance.navigation.type
property to check what kind of navigation is done.
If the value is 1, then we refreshed the page manually with the F5 key.
For instance, we write:
import React, { useEffect } from "react";
export default function App() {
useEffect(() => {
if (performance.navigation.type === 1) {
console.log("This page is reloaded");
} else {
console.log("This page is not reloaded");
}
});
return <div></div>;
}
We check that the performance.navigation.type
value is 1.
If it is, we log 'This page is reloaded'
.
This code is in a function in the useEffect
hook so that it runs every time rendering is done.
Therefore, when we press F5 to refresh, we should see 'This page is reloaded'
logged in the console.
Conclusion
To detect page refresh by pressing F5 in a React component, we can use the performance.navigation.type
property to check what kind of navigation is done.
If the value is 1, then we refreshed the page manually with the F5 key.