babel-plugin-transform-react-pure-components
v3.1.2
Published
Optimize React code by transforming pure components into stateless functional components.
Downloads
73
Maintainers
Readme
babel-plugin-transform-react-pure-components
Optimize React code by transforming pure components into stateless functional components.
Introduction
In React, a pure component is a component that renders the same given the same properties and state. In addition stateless functions can replace class-based components that only rely on properties.
This Babel plugin transforms class-based components into stateless functions, if:
- The class only contains a
render()
method. - Does not define additional (static) properties.
- Is stateless.
Example
In:
class MyComponent extends React.Component {
static propTypes = {
className: React.PropTypes.string.isRequired
};
render() {
return (
<div className={this.props.className}>
...
</div>
);
}
}
Out:
function MyComponent(props) {
return (
<div className={props.className}>
...
</div>
);
}
MyComponent.propTypes = {
className: React.PropTypes.string.isRequired
};
Installation
$ npm install babel-plugin-transform-react-pure-components
Usage
Via .babelrc
(Recommended)
.babelrc
{
"plugins": ["transform-react-pure-components"]
}
Via CLI
$ babel --plugins transform-react-pure-components script.js
Via Node API
require("babel-core").transform("code", {
plugins: ["transform-react-pure-components"]
});
Options
The options below may not improve performance, and may produce unpredictable results.
pureComponents = false
— Transform components extendingReact.PureComponent
classes (this effectively converts them back toReact.Component
).assignDefaultProps = false
— When true, useObject.assign(defaultProps, props)
instead of an additional static definition. Set tohoist
to hoist them to the parent scope (can be useful in combination with babel-plugin-transform-react-remove-prop-types).
Benchmarks
According to this article, a performance boost can be expected. However, another article shows no performance boost. Nonetheless, functional stateless components may allow for optimizations in the future.
In a (non-scientific) benchmark, using this plugin yields an improvement of 22% over a class-based component (React 16, 10.000 instantiations of a component, babel-preset-env @ Chrome 59).