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:
Component static propTypes = className: ReactPropTypesstringisRequired ; { return <div className=thispropsclassName> ... </div> ; }
Out:
{ return <div className=propsclassName> ... </div> ;} MyComponentpropTypes = className: ReactPropTypesstringisRequired;
Installation
$ npm install babel-plugin-transform-react-pure-components
Usage
.babelrc
(Recommended)
Via .babelrc
Via CLI
$ babel --plugins transform-react-pure-components script.js
Via Node API
;
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).