Skip to content

Instantly share code, notes, and snippets.

@joscha
Last active May 2, 2019 21:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joscha/9e1d4eea6fddd50df25012d704180aa1 to your computer and use it in GitHub Desktop.
Save joscha/9e1d4eea6fddd50df25012d704180aa1 to your computer and use it in GitHub Desktop.
React Storybook example for stats.js integration
import { configure, setAddon } from '@kadira/storybook';
import MonitoredStory from './MonitoredStory.js';
setAddon({
addMonitored(storyName, storyFn, rafFn) {
this.add(storyName, (context) => (
<MonitoredStory rafFn={rafFn}>
{storyFn(context)}
</MonitoredStory>
));
},
});
configure(loadStories, module);
storiesOf('something', module)
.addMonitored('a component with monitored performance', () => (
<Component />
), () => {
// This is where the actual work is done - anything in here will be monitored by the stats
// view and displayed, so this is where you want to do your animation work, etc.
const x = Math.random() * 1000000;
for (let i = 0; i < x; i++) {
Math.random(); // burn some CPU cycles
}
});
import React from 'react';
import Stats from 'stats.js';
const { requestAnimationFrame, cancelAnimationFrame } = window;
class MonitoredStory extends React.Component {
constructor(...args) {
super(...args);
this.rafFn = () => null; // noop
}
componentDidMount() {
const stats = new Stats();
stats.showPanel(0);
this.refs.stats.appendChild(stats.dom);
const animate = () => {
stats.begin();
this.props.rafFn();
stats.end();
this.rafPointer = requestAnimationFrame(animate);
};
this.rafPointer = requestAnimationFrame(animate);
}
componentWillUnmount() {
cancelAnimationFrame(this.rafPointer);
}
render() {
return (
<div ref="stats">
{this.props.children}
</div>
);
}
}
MonitoredStory.displayName = 'MonitoredStory';
MonitoredStory.propTypes = {
children: React.PropTypes.node.isRequired,
rafFn: React.PropTypes.func,
};
export default MonitoredStory;
{
"dependencies": {
"stats.js": "^0.16.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment