babel-plugin-transform-react-pure-components

3.1.2 • Public • Published

babel-plugin-transform-react-pure-components

Optimize React code by transforming pure components into stateless functional components.

Build Status

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 extending React.PureComponent classes (this effectively converts them back to React.Component).
  • assignDefaultProps = false — When true, use Object.assign(defaultProps, props) instead of an additional static definition. Set to hoist 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).

Package Sidebar

Install

npm i babel-plugin-transform-react-pure-components

Weekly Downloads

125

Version

3.1.2

License

MIT

Last publish

Collaborators

  • basilfx