Modern Methods for Detecting Page Refresh in React: From Performance API to Lifecycle Management

Dec 04, 2025 · Programming · 12 views · 7.8

Keywords: React | Page Refresh Detection | Performance API | beforeunload Event | Lifecycle Management

Abstract: This article explores various technical solutions for detecting page refresh (F5 or refresh button) in React applications. By analyzing the best answer (based on Performance API) and supplementary methods from Q&A data, it systematically introduces beforeunload event listening, the use of Performance.navigation.type and its deprecation status, and integration strategies with React lifecycle and Hooks. The article explains the implementation principles, applicable scenarios, and potential limitations of each method, providing complete code examples and best practice recommendations to help developers choose the most suitable solution based on specific needs.

Introduction and Problem Background

In single-page application (SPA) development, particularly with the React framework, detecting page refresh is a common yet challenging requirement. When users trigger a page refresh via the browser refresh button or F5 key, applications need to identify this event to execute specific logic, such as data saving, state restoration, or user behavior analysis. However, due to browser security restrictions and React's component-based nature, directly capturing refresh events is not straightforward. Based on technical discussions from Q&A data, this article systematically introduces multiple detection methods, with a focus on analyzing the implementation of the best answer.

Core Method: Application of Performance API

The best answer (Answer 2) in the Q&A data recommends using the Performance.navigation.type property to detect page refresh. This method leverages the Performance API provided by browsers, determining whether a page has been reloaded by checking the navigation type. The specific implementation is as follows:

if (window.performance) {
  if (performance.navigation.type == 1) {
    alert("This page is reloaded");
  } else {
    alert("This page is not reloaded");
  }
}

The code first checks for the existence of the window.performance object to ensure browser support for the Performance API. Then, it evaluates the value of performance.navigation.type: a value of 1 indicates the page was reloaded via a refresh operation; other values correspond to different navigation types (e.g., 0 for navigation via links). This approach is simple and direct, requiring no complex event listeners, making it suitable for scenarios where immediate detection of refresh is needed during component initialization.

Method Limitations: Deprecation Status and Alternatives

Although Performance.navigation.type is effective in practice, Answer 4 notes that this API has been deprecated. According to W3C specifications, the performance.navigation property is no longer recommended, and developers should transition to more modern APIs, such as Navigation Timing Level 2. However, as the new API is still experimental, alternative solutions may be necessary in current projects. A common practice is to combine state management (e.g., Redux) to track page state: set a flag during application initialization and distinguish between refresh and normal navigation through route changes or component lifecycle events. For example, in React, initial state can be saved in the root component or route handler and updated during subsequent interactions.

Supplementary Method: beforeunload Event Listening

Answer 1 and Answer 3 provide solutions based on the beforeunload event. This method captures refresh operations by listening to the event before window unload, suitable for scenarios requiring cleanup or user prompts before refresh. In React functional components, the useEffect Hook can be used to manage event listeners:

useEffect(() => {
    window.addEventListener("beforeunload", alertUser);
    return () => {
      window.removeEventListener("beforeunload", alertUser);
    };
  }, []);
  const alertUser = (e) => {
    e.preventDefault();
    e.returnValue = "";
  };

In class components, similar logic can be implemented via componentDidMount and componentWillUnmount lifecycle methods. It is important to note that the beforeunload event is triggered not only by refresh but also by page closure or navigation, so additional logic may be needed to distinguish specific actions. Moreover, modern browsers impose strict limitations on handling beforeunload events, such as prohibiting custom popup content and only allowing default prompts.

Advanced Integration: Conditional Event Handling

Answer 3 further extends the beforeunload method by introducing conditional event handling. By adding validation logic, developers can trigger refresh detection only under specific conditions (e.g., when a form is unsaved). In functional components, this can be achieved via dependency arrays:

useEffect(() => {
    if (condition) {
        window.onbeforeunload = function() {
            return true;
        };
    }
    return () => {
        window.onbeforeunload = null;
    };
}, [condition]);

This approach enhances code flexibility and performance by avoiding unnecessary listener bindings. In class components, dynamic adjustment of event handling can be done through componentDidUpdate.

Practical Recommendations and Best Practices

Based on the Q&A data, the following factors should be considered when selecting a detection method: browser compatibility, React version (class vs. functional components), and specific use cases. For simple detection, the Performance API offers a quick solution, but its deprecation status must be noted; for scenarios requiring pre-processing operations, the beforeunload event is more appropriate, but browser differences should be handled. It is recommended to combine multiple methods in projects, such as using the Performance API for initial detection supplemented by state management to track user interactions. Additionally, error handling should be included in the code, such as checking API support to avoid runtime errors.

Conclusion

Detecting page refresh in React is a multifaceted issue involving browser APIs, React lifecycle, and event handling. By analyzing Q&A data, this article systematically introduces two main methods—Performance API and beforeunload events—and discusses their implementation details, limitations, and best practices. Developers should choose appropriate solutions based on project requirements and stay informed about the evolution of web standards to ensure ongoing compatibility and performance. As new APIs mature, more elegant solutions may emerge in the future.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.