Skip to content

Instantly share code, notes, and snippets.

@badsyntax
Created April 25, 2015 17:36
Show Gist options
  • Select an option

  • Save badsyntax/4f8ed3fca9fffa921596 to your computer and use it in GitHub Desktop.

Select an option

Save badsyntax/4f8ed3fca9fffa921596 to your computer and use it in GitHub Desktop.
A basic example of how to benchmark react component render times.
'use strict';
import _ from 'lodash';
import React from 'react';
import AppActions from '../../actions/AppActions';
import NewsStore from '../../stores/NewsStore';
import { NewsList } from '../';
let { Perf } = React.addons;
function getState(state) {
return _.merge({
posts: NewsStore.getAll(),
isLoading: true
}, state);
}
class NewsPage extends React.Component {
constructor(...args) {
super(...args);
this.state = getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
NewsStore.addChangeListener(this.onChange);
AppActions.getNews();
}
componentWillUnmount() {
NewsStore.removeChangeListener(this.onChange);
}
onChange() {
Perf.start();
this.setState(getState({
isLoading: false
}));
Perf.stop();
Perf.printInclusive();
Perf.printWasted();
}
getNewsList() {
return (
<NewsList
hasError={this.state.hasError}
isLoading={this.state.isLoading}
posts={this.state.posts} />
);
}
render() {
return (
<div className={'mui-app-content-canvas'}>
{this.getNewsList()}
</div>
);
}
}
export default NewsPage;
@richardscarrott
Copy link

I'm not sure this would be testing the render time as setState is batched in event handlers meaning not only has the DOM not been updated the components render method hasn't even been called by the time you call Perf.stop.

I think it would be better to call Perf.start in componentWillMount / componentWillUpdate and call Perf.stop in componentDidMount / componentDidUpdate as then you can be sure the render operations have been flushed to the DOM.

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