Skip to content

Instantly share code, notes, and snippets.

@usrbowe
Created November 10, 2018 11:37
Show Gist options
  • Save usrbowe/7de2320617d7c47411a80c58a22a0180 to your computer and use it in GitHub Desktop.
Save usrbowe/7de2320617d7c47411a80c58a22a0180 to your computer and use it in GitHub Desktop.
React Native Profiler
import React, {Component} from "react"
import {Text, View} from "react-native"
import firebase from "react-native-firebase"
const Profiler = React.unstable_Profiler
export default class App extends Component {
constructor(props) {
super(props)
this.trace = null
this.traceStarted = false
this.initialMount = null
this.initialUpdates = null
}
async componentDidMount() {
this.trace = firebase.perf().newTrace("cache_trace")
await this.trace.start()
this.traceStarted = true
// put cached values after trace started
await this.trace.putAttribute("mount_time", this.initialMount)
if (this.initialUpdates) await this.trace.incrementMetric("updates", this.initialUpdates)
}
async componentWillUnmount() {
await this.trace.stop()
}
logMeasurement = async (id, phase, actualDuration, baseDuration) => {
// see output during DEV
if (__DEV__) console.log({id, phase, actualDuration, baseDuration})
if (phase === "mount") {
if (this.traceStarted) {
await this.trace.putAttribute("mount_time", actualDuration)
} else {
// cache mount time before trace.start()
this.initialMount = actualDuration
}
} else if (phase === "update") {
if (this.traceStarted) {
await this.trace.incrementMetric("updates", 1)
} else {
// cache updates before trace.start()
this.initialUpdates = this.initialUpdates + 1
}
}
}
render() {
return (
<Profiler id={"HomeScreen"} onRender={this.logMeasurement}>
<View>
<Text>Welcome to React Native!</Text>
</View>
</Profiler>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment