@babel/plugin-transform-react-constant-elements

This plugin can speed up reconciliation and reduce garbage collection pressure by hoistingReact elements to the highest possible scope, preventing multiple unnecessary reinstantiations.

Example

In

  1. const Hr = () => {
  2. return <hr className="hr" />;
  3. };

Out

  1. const _ref = <hr className="hr" />;
  2. const Hr = () => {
  3. return _ref;
  4. };

Deopts

  • Spread Operator
  1. <div {...foobar} />
  • Refs
  1. <div ref="foobar" />
  2. <div ref={node => this.node = node} />
  • Mutable Properties

See https://github.com/facebook/react/issues/3226 for more on this

  1. <div style={{width: 100}} />

Installation

  1. npm install --save-dev @babel/plugin-transform-react-constant-elements

Usage

.babelrc

  1. {
  2. "plugins": ["@babel/plugin-transform-react-constant-elements"]
  3. }

Options

allowMutablePropsOnTags

Array<string>, defaults to []

If you are using a particular library (like react-intl) that uses object properties, and you are surethat the element won't modify its own props, you can whitelist the element so that objects are allowed.

This will skip the Mutable Properties deopt.

  1. {
  2. "plugins": [
  3. ["@babel/plugin-transform-react-constant-elements", {"allowMutablePropsOnTags": ["FormattedMessage"]}],
  4. ]
  5. }

You can read more about configuring plugin options here

Via CLI

  1. babel --plugins @babel/plugin-transform-react-constant-elements script.js

Via Node API

  1. require("@babel/core").transform("code", {
  2. plugins: ["@babel/plugin-transform-react-constant-elements"]
  3. });

References