Skip to content

Instantly share code, notes, and snippets.

@jaredLunde
Last active July 28, 2016 03:03
Show Gist options
  • Save jaredLunde/ffb3209e8ad64cf7a41641da1f886b41 to your computer and use it in GitHub Desktop.
Save jaredLunde/ffb3209e8ad64cf7a41641da1f886b41 to your computer and use it in GitHub Desktop.
ES2015 React HOC for performance benchmarking using the React addon 'Perf'
// Pre-requisites
// ```````````````
// npm i react --save
// npm i react-addons-perf --save-dev
//
//
// Plain render usage
// ```````````````````
// const YourPerfComponent = withPerf(YourComponent)
// React.render(React.createElement(YourPerfComponent, props, children), ...)
//
//
// React Router
// `````````````
// <Router history='...'>
// <Router path='/' component={withPerf(YourComponent)}/>
// </Router>
//
//
// You may also optionally decorate your component with es6 decorators
// and the provided TestPerf decorator like:
//
// @TestPerf
// class YourComponent extends React.Component {
// ...
// }
import React from 'react'
import Perf from 'react-addons-perf'
const withPerf = (Component) => {
const displayName = `withPerf(${Component.displayName})`
return class PerfComponent extends React.Component {
static displayName = displayName
componentWillMount () {
console.log("Mounting:", displayName)
Perf.start()
}
componentDidMount () {
console.log("Mounted:", displayName)
Perf.stop()
Perf.printInclusive()
Perf.printWasted()
}
componentWillUpdate () {
console.log("Updating:", displayName)
Perf.start()
}
componentDidUpdate () {
console.log("Updated:", displayName)
Perf.stop()
Perf.printInclusive()
Perf.printWasted()
}
render () {
return <Component {...this.props}/>
}
}
}
const TestPerf = () => (Component) => withPerf(Component)
@jaredLunde
Copy link
Author

Heads up for the unaware - if your aim is to profile each of your app's components, you only have to include withPerf(...) on your OUTERmost component. So when using React Router or similar libraries, on your App component. Perf prints information for each child component to the console.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment