skip to Main Content

There is React application with one route. I make several API requests to get data from backend. While fetching I show loading spinner and actual data after successful requests. I need to get time in milliseconds how much time did it take to get all files (like js files and so on), make requests and display data. How can I do that? I see there is Performance API but it seems to be deprecated.

I tried to use Performance API but it’s deprecated.

2

Answers


  1. Absolutely! You can indeed use the getTime function to get the timestamp before and after making the API call to calculate the API response time.

      const startTime = new Date().getTime();
      fetch('your-api-endpoint')
      .then(response => response.json())
      .then(data => {
        const endTime = new Date().getTime();
        const apiResponseTime = endTime - startTime; 
        console.log("res:", apiResponseTime, "ms");
      })
      .catch(error => {
        console.error('err', error);
      });
    
    Login or Signup to reply.
  2. Using console.time and console.timeEnd:

    console.time('data-fetch');
    
    // Your data fetching logic (API requests, state updates)
    
    console.timeEnd('data-fetch');
    
    // Output: data-fetch: 1234.567ms
    enter code here
    

    Using PerformanceObserver

    Create a new PerformanceObserver instance with the ‘navigation‘ entry type

    const observer = new PerformanceObserver((list) => {
      const { domContentLoadedEventEnd } = list.getEntries()[0];
      const renderTime = performance.now() - domContentLoadedEventEnd;
      console.log('Render time:', renderTime);
    });
    observer.observe({ type: 'navigation' });
    

    Using Third-Party Libraries

    Libraries like react-performance-wrapper or react-perf can provide more detailed performance insights and profiling capabilities within your React components

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search