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

This plugin can speed up reconciliation and reduce garbage collection pressure by hoisting React 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

  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 sure that the element won’t modify its own props, you can permit objects to be allowed for specific elements.

This will skip the Mutable Properties deopt.

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

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").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-react-constant-elements"],
  3. });

References