'Calculating time to mount the screen in React Native

There was a couple of questions that are related to this topic but none of them has a proper answer. So what I want to do is calculating the time to navigate to a screen. so basically timer starts here ;

navigation.navigate("SomePage")

so it should start some kind of timer every time the navigation function is fired.

I can end the timer on NavigationContainer with onStateChange;

<NavigationContainer
        ref={navigationRef}
        onStateChange={() => // I can end timer here}
      >

So how can we do this?



Solution 1:[1]

Are you concerned with the time of navigation, or the time mounting the screen? I think the time of navigation will be negligible, and mounting will always be the costly operation.

React 16.9 made the Profiler component stable, which includes an API for measuring mount times of whole screens or even subsets of screens. You would wrap the component(s) you want to measure in the Profiler component:

import React, { Profiler } from 'react';
...

<Profiler onRender={onRender}>
  <View>
    ...
</Profiler>

The onRender prop is required, and has the following signature (as of React 17.0.1, which is bundled with RN 64):

function onRenderCallback(
  id, // the "id" prop of the Profiler tree that has just committed
  phase, // either "mount" (if the tree just mounted) or "update" (if it re-rendered)
  actualDuration, // time spent rendering the committed update
  baseDuration, // estimated time to render the entire subtree without memoization
  startTime, // when React began rendering this update
  commitTime, // when React committed this update
  interactions // the Set of interactions belonging to this update
) {
  // Aggregate or log render timings...
}

Probably the easiest way is to subtract startTime from commitTime when the phase is 'mount'.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abe