Mixins Considered Harmful

July 13, 2016 by Dan Abramov


“How do I share the code between several components?” is one of the first questions that people ask when they learn React. Our answer has always been to use component composition for code reuse. You can define a component and use it in several other components.

It is not always obvious how a certain pattern can be solved with composition. React is influenced by functional programming but it came into the field that was dominated by object-oriented libraries. It was hard for engineers both inside and outside of Facebook to give up on the patterns they were used to.

To ease the initial adoption and learning, we included certain escape hatches into React. The mixin system was one of those escape hatches, and its goal was to give you a way to reuse code between components when you aren’t sure how to solve the same problem with composition.

Three years passed since React was released. The landscape has changed. Multiple view libraries now adopt a component model similar to React. Using composition over inheritance to build declarative user interfaces is no longer a novelty. We are also more confident in the React component model, and we have seen many creative uses of it both internally and in the community.

In this post, we will consider the problems commonly caused by mixins. Then we will suggest several alternative patterns for the same use cases. We have found those patterns to scale better with the complexity of the codebase than mixins.

Why Mixins are Broken #

At Facebook, React usage has grown from a few components to thousands of them. This gives us a window into how people use React. Thanks to declarative rendering and top-down data flow, many teams were able to fix a bunch of bugs while shipping new features as they adopted React.

However it’s inevitable that some of our code using React gradually became incomprehensible. Occasionally, the React team would see groups of components in different projects that people were afraid to touch. These components were too easy to break accidentally, were confusing to new developers, and eventually became just as confusing to the people who wrote them in the first place. Much of this confusion was caused by mixins. At the time, I wasn’t working at Facebook but I came to the same conclusions after writing my fair share of terrible mixins.

This doesn’t mean that mixins themselves are bad. People successfully employ them in different languages and paradigms, including some functional languages. At Facebook, we extensively use traits in Hack which are fairly similar to mixins. Nevertheless, we think that mixins are unnecessary and problematic in React codebases. Here’s why.

Mixins introduce implicit dependencies #

Sometimes a component relies on a certain method defined in the mixin, such as getClassName(). Sometimes it’s the other way around, and mixin calls a method like renderHeader() on the component. JavaScript is a dynamic language so it’s hard to enforce or document these dependencies.

Mixins break the common and usually safe assumption that you can rename a state key or a method by searching for its occurrences in the component file. You might write a stateful component and then your coworker might add a mixin that reads this state. In a few months, you might want to move that state up to the parent component so it can be shared with a sibling. Will you remember to update the mixin to read a prop instead? What if, by now, other components also use this mixin?

These implicit dependencies make it hard for new team members to contribute to a codebase. A component’s render() method might reference some method that isn’t defined on the class. Is it safe to remove? Perhaps it’s defined in one of the mixins. But which one of them? You need to scroll up to the mixin list, open each of those files, and look for this method. Worse, mixins can specify their own mixins, so the search can be deep.

Often, mixins come to depend on other mixins, and removing one of them breaks the other. In these situations it is very tricky to tell how the data flows in and out of mixins, and what their dependency graph looks like. Unlike components, mixins don’t form a hierarchy: they are flattened and operate in the same namespace.

Mixins cause name clashes #

There is no guarantee that two particular mixins can be used together. For example, if FluxListenerMixin defines handleChange() and WindowSizeMixin defines handleChange(), you can’t use them together. You also can’t define a method with this name on your own component.

It’s not a big deal if you control the mixin code. When you have a conflict, you can rename that method on one of the mixins. However it’s tricky because some components or other mixins may already be calling this method directly, and you need to find and fix those calls as well.

If you have a name conflict with a mixin from a third party package, you can’t just rename a method on it. Instead, you have to use awkward method names on your component to avoid clashes.

The situation is no better for mixin authors. Even adding a new method to a mixin is always a potentially breaking change because a method with the same name might already exist on some of the components using it, either directly or through another mixin. Once written, mixins are hard to remove or change. Bad ideas don’t get refactored away because refactoring is too risky.

Mixins cause snowballing complexity #

Even when mixins start out simple, they tend to become complex over time. The example below is based on a real scenario I’ve seen play out in a codebase.

A component needs some state to track mouse hover. To keep this logic reusable, you might extract handleMouseEnter(), handleMouseLeave() and isHovering() into a HoverMixin. Next, somebody needs to implement a tooltip. They don’t want to duplicate the logic in HoverMixin so they create a TooltipMixin that uses HoverMixin. TooltipMixin reads isHovering() provided by HoverMixin in its componentDidUpdate() and either shows or hides the tooltip.

A few months later, somebody wants to make the tooltip direction configurable. In an effort to avoid code duplication, they add support for a new optional method called getTooltipOptions() to TooltipMixin. By this time, components that show popovers also use HoverMixin. However popovers need a different hover delay. To solve this, somebody adds support for an optional getHoverOptions() method and implements it in TooltipMixin. Those mixins are now tightly coupled.

This is fine while there are no new requirements. However this solution doesn’t scale well. What if you want to support displaying multiple tooltips in a single component? You can’t define the same mixin twice in a component. What if the tooltips need to be displayed automatically in a guided tour instead of on hover? Good luck decoupling TooltipMixin from HoverMixin. What if you need to support the case where the hover area and the tooltip anchor are located in different components? You can’t easily hoist the state used by mixin up into the parent component. Unlike components, mixins don’t lend themselves naturally to such changes.

Every new requirement makes the mixins harder to understand. Components using the same mixin become increasingly coupled with time. Any new capability gets added to all of the components using that mixin. There is no way to split a “simpler” part of the mixin without either duplicating the code or introducing more dependencies and indirection between mixins. Gradually, the encapsulation boundaries erode, and since it’s hard to change or remove the existing mixins, they keep getting more abstract until nobody understands how they work.

These are the same problems we faced building apps before React. We found that they are solved by declarative rendering, top-down data flow, and encapsulated components. At Facebook, we have been migrating our code to use alternative patterns to mixins, and we are generally happy with the results. You can read about those patterns below.

Migrating from Mixins #

Let’s make it clear that mixins are not technically deprecated. If you use React.createClass(), you may keep using them. We only say that they didn’t work well for us, and so we won’t recommend using them in the future.

Every section below corresponds to a mixin usage pattern that we found in the Facebook codebase. For each of them, we describe the problem and a solution that we think works better than mixins. The examples are written in ES5 but once you don’t need mixins, you can switch to ES6 classes if you’d like.

We hope that you find this list helpful. Please let us know if we missed important use cases so we can either amend the list or be proven wrong!

Performance Optimizations #

One of the most commonly used mixins is PureRenderMixin. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:

var PureRenderMixin = require('react-addons-pure-render-mixin');

var Button = React.createClass({
  mixins: [PureRenderMixin],

  // ...

});

Solution #

To express the same without mixins, you can use the shallowCompare function directly instead:

var shallowCompare = require('react-addons-shallow-compare');

var Button = React.createClass({
  shouldComponentUpdate: function(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  },

  // ...

});

If you use a custom mixin implementing a shouldComponentUpdate function with different algorithm, we suggest exporting just that single function from a module and calling it directly from your components.

We understand that more typing can be annoying. For the most common case, we plan to introduce a new base class called React.PureComponent in the next minor release. It uses the same shallow comparison as PureRenderMixin does today.

Subscriptions and Side Effects #

The second most common type of mixins that we encountered are mixins that subscribe a React component to a third-party data source. Whether this data source is a Flux Store, an Rx Observable, or something else, the pattern is very similar: the subscription is created in componentDidMount, destroyed in componentWillUnmount, and the change handler calls this.setState().

var SubscriptionMixin = {
  getInitialState: function() {
    return {
      comments: DataSource.getComments()
    };
  },

  componentDidMount: function() {
    DataSource.addChangeListener(this.handleChange);
  },

  componentWillUnmount: function() {
    DataSource.removeChangeListener(this.handleChange);
  },

  handleChange: function() {
    this.setState({
      comments: DataSource.getComments()
    });
  }
};

var CommentList = React.createClass({
  mixins: [SubscriptionMixin],

  render: function() {
    // Reading comments from state managed by mixin.
    var comments = this.state.comments;
    return (
      <div>
        {comments.map(function(comment) {
          return <Comment comment={comment} key={comment.id} />
        })}
      </div>
    )
  }
});

module.exports = CommentList;

Solution #

If there is just one component subscribed to this data source, it is fine to embed the subscription logic right into the component. Avoid premature abstractions.

If several components used this mixin to subscribe to a data source, a nice way to avoid repetition is to use a pattern called “higher-order components”. It can sound intimidating so we will take a closer look at how this pattern naturally emerges from the component model.

Higher-Order Components Explained #

Let’s forget about React for a second. Consider these two functions that add and multiply numbers, logging the results as they do that:

function addAndLog(x, y) {
  var result = x + y;
  console.log('result:', result);
  return result;
}

function multiplyAndLog(x, y) {
  var result = x * y;
  console.log('result:', result);
  return result;
}

These two functions are not very useful but they help us demonstrate a pattern that we can later apply to components.

Let’s say that we want to extract the logging logic out of these functions without changing their signatures. How can we do this? An elegant solution is to write a higher-order function, that is, a function that takes a function as an argument and returns a function.

Again, it sounds more intimidating than it really is:

function withLogging(wrappedFunction) {
  // Return a function with the same API...
  return function(x, y) {
    // ... that calls the original function
    var result = wrappedFunction(x, y);
    // ... but also logs its result!
    console.log('result:', result);
    return result;
  };
}

The withLogging higher-order function lets us write add and multiply without the logging statements, and later wrap them to get addAndLog and multiplyAndLog with exactly the same signatures as before:

function add(x, y) {
  return x + y;
}

function multiply(x, y) {
  return x * y;
}

function withLogging(wrappedFunction) {
  return function(x, y) {
    var result = wrappedFunction(x, y);
    console.log('result:', result);
    return result;
  };
}

// Equivalent to writing addAndLog by hand:
var addAndLog = withLogging(add);

// Equivalent to writing multiplyAndLog by hand:
var multiplyAndLog = withLogging(multiply);

Higher-order components are a very similar pattern, but applied to components in React. We will apply this transformation from mixins in two steps.

As a first step, we will split our CommentList component in two, a child and a parent. The child will be only concerned with rendering the comments. The parent will set up the subscription and pass the up-to-date data to the child via props.

// This is a child component.
// It only renders the comments it receives as props.
var CommentList = React.createClass({
  render: function() {
    // Note: now reading from props rather than state.
    var comments = this.props.comments;
    return (
      <div>
        {comments.map(function(comment) {
          return <Comment comment={comment} key={comment.id} />
        })}
      </div>
    )
  }
});

// This is a parent component.
// It subscribes to the data source and renders <CommentList />.
var CommentListWithSubscription = React.createClass({
  getInitialState: function() {
    return {
      comments: DataSource.getComments()
    };
  },

  componentDidMount: function() {
    DataSource.addChangeListener(this.handleChange);
  },

  componentWillUnmount: function() {
    DataSource.removeChangeListener(this.handleChange);
  },

  handleChange: function() {
    this.setState({
      comments: DataSource.getComments()
    });
  },

  render: function() {
    // We pass the current state as props to CommentList.
    return <CommentList comments={this.state.comments} />;
  }
});

module.exports = CommentListWithSubscription;

There is just one final step left to do.

Remember how we made withLogging() take a function and return another function wrapping it? We can apply a similar pattern to React components.

We will write a new function called withSubscription(WrappedComponent). Its argument could be any React component. We will pass CommentList as WrappedComponent, but we could also apply withSubscription() to any other component in our codebase.

This function would return another component. The returned component would manage the subscription and render <WrappedComponent /> with the current data.

We call this pattern a “higher-order component”.

The composition happens at React rendering level rather than with a direct function call. This is why it doesn’t matter whether the wrapped component is defined with createClass(), as an ES6 class or a function. If WrappedComponent is a React component, the component created by withSubscription() can render it.

// This function takes a component...
function withSubscription(WrappedComponent) {
  // ...and returns another component...
  return React.createClass({
    getInitialState: function() {
      return {
        comments: DataSource.getComments()
      };
    },

    componentDidMount: function() {
      // ... that takes care of the subscription...
      DataSource.addChangeListener(this.handleChange);
    },

    componentWillUnmount: function() {
      DataSource.removeChangeListener(this.handleChange);
    },

    handleChange: function() {
      this.setState({
        comments: DataSource.getComments()
      });
    },

    render: function() {
      // ... and renders the wrapped component with the fresh data!
      return <WrappedComponent comments={this.state.comments} />;
    }
  });
}

Now we can declare CommentListWithSubscription by applying withSubscription to CommentList:

var CommentList = React.createClass({
  render: function() {
    var comments = this.props.comments;
    return (
      <div>
        {comments.map(function(comment) {
          return <Comment comment={comment} key={comment.id} />
        })}
      </div>
    )
  }
});

// withSubscription() returns a new component that
// is subscribed to the data source and renders
// <CommentList /> with up-to-date data.
var CommentListWithSubscription = withSubscription(CommentList);

// The rest of the app is interested in the subscribed component
// so we export it instead of the original unwrapped CommentList.
module.exports = CommentListWithSubscription;

Solution, Revisited #

Now that we understand higher-order components better, let’s take another look at the complete solution that doesn’t involve mixins. There are a few minor changes that are annotated with inline comments:

function withSubscription(WrappedComponent) {
  return React.createClass({
    getInitialState: function() {
      return {
        comments: DataSource.getComments()
      };
    },

    componentDidMount: function() {
      DataSource.addChangeListener(this.handleChange);
    },

    componentWillUnmount: function() {
      DataSource.removeChangeListener(this.handleChange);
    },

    handleChange: function() {
      this.setState({
        comments: DataSource.getComments()
      });
    },

    render: function() {
      // Use JSX spread syntax to pass all props and state down automatically.
      return <WrappedComponent {...this.props} {...this.state} />;
    }
  });
}

// Optional change: convert CommentList to a functional component
// because it doesn't use lifecycle hooks or state.
function CommentList(props) {
  var comments = props.comments;
  return (
    <div>
      {comments.map(function(comment) {
        return <Comment comment={comment} key={comment.id} />
      })}
    </div>
  )
}

// Instead of declaring CommentListWithSubscription,
// we export the wrapped component right away.
module.exports = withSubscription(CommentList);

Higher-order components are a powerful pattern. You can pass additional arguments to them if you want to further customize their behavior. After all, they are not even a feature of React. They are just functions that receive components and return components that wrap them.

Like any solution, higher-order components have their own pitfalls. For example, if you heavily use refs, you might notice that wrapping something into a higher-order component changes the ref to point to the wrapping component. In practice we discourage using refs for component communication so we don’t think it’s a big issue. In the future, we might consider adding ref forwarding to React to solve this annoyance.

Rendering Logic #

The next most common use case for mixins that we discovered in our codebase is sharing rendering logic between components.

Here is a typical example of this pattern:

var RowMixin = {
  // Called by components from render()
  renderHeader: function() {
    return (
      <div className='row-header'>
        <h1>
          {this.getHeaderText() /* Defined by components */}
        </h1>
      </div>
    );
  }
};

var UserRow = React.createClass({
  mixins: [RowMixin],

  // Called by RowMixin.renderHeader()
  getHeaderText: function() {
    return this.props.user.fullName;
  },

  render: function() {
    return (
      <div>
        {this.renderHeader() /* Defined by RowMixin */}
        <h2>{this.props.user.biography}</h2>
      </div>
    )
  }
});

Multiple components may be sharing RowMixin to render the header, and each of them would need to define getHeaderText().

Solution #

If you see rendering logic inside a mixin, it’s time to extract a component!

Instead of RowMixin, we will define a <Row> component. We will also replace the convention of defining a getHeaderText() method with the standard mechanism of top-data flow in React: passing props.

Finally, since neither of those components currently need lifecycle hooks or state, we can declare them as simple functions:

function RowHeader(props) {
  return (
    <div className='row-header'>
      <h1>{props.text}</h1>
    </div>
  );
}

function UserRow(props) {
  return (
    <div>
      <RowHeader text={props.user.fullName} />
      <h2>{props.user.biography}</h2>
    </div>
  );
}

Props keep component dependencies explicit, easy to replace, and enforceable with tools like Flow and TypeScript.

Note:

Defining components as functions is not required. There is also nothing wrong with using lifecycle hooks and state—they are first-class React features. We use functional components in this example because they are easier to read and we didn’t need those extra features, but classes would work just as fine.

Context #

Another group of mixins we discovered were helpers for providing and consuming React context. Context is an experimental unstable feature, has certain issues, and will likely change its API in the future. We don’t recommend using it unless you’re confident there is no other way of solving your problem.

Nevertheless, if you already use context today, you might have been hiding its usage with mixins like this:

var RouterMixin = {
  contextTypes: {
    router: React.PropTypes.object.isRequired
  },

  // The mixin provides a method so that components
  // don't have to use the context API directly.
  push: function(path) {
    this.context.router.push(path)
  }
};

var Link = React.createClass({
  mixins: [RouterMixin],

  handleClick: function(e) {
    e.stopPropagation();

    // This method is defined in RouterMixin.
    this.push(this.props.to);
  },

  render: function() {
    return (
      <a onClick={this.handleClick}>
        {this.props.children}
      </a>
    );
  }
});

module.exports = Link;

Solution #

We agree that hiding context usage from consuming components is a good idea until the context API stabilizes. However, we recommend using higher-order components instead of mixins for this.

Let the wrapping component grab something from the context, and pass it down with props to the wrapped component:

function withRouter(WrappedComponent) {
  return React.createClass({
    contextTypes: {
      router: React.PropTypes.object.isRequired
    },

    render: function() {
      // The wrapper component reads something from the context
      // and passes it down as a prop to the wrapped component.
      var router = this.context.router;
      return <WrappedComponent {...this.props} router={router} />;
    }
  });
};

var Link = React.createClass({
  handleClick: function(e) {
    e.stopPropagation();

    // The wrapped component uses props instead of context.
    this.props.router.push(this.props.to);
  },

  render: function() {
    return (
      <a onClick={this.handleClick}>
        {this.props.children}
      </a>
    );
  }
});

// Don't forget to wrap the component!
module.exports = withRouter(Link);

If you’re using a third party library that only provides a mixin, we encourage you to file an issue with them linking to this post so that they can provide a higher-order component instead. In the meantime, you can create a higher-order component around it yourself in exactly the same way.

Utility Methods #

Sometimes, mixins are used solely to share utility functions between components:

var ColorMixin = {
  getLuminance(color) {
    var c = parseInt(color, 16);
    var r = (c & 0xFF0000) >> 16;
    var g = (c & 0x00FF00) >> 8;
    var b = (c & 0x0000FF);
    return (0.299 * r + 0.587 * g + 0.114 * b);
  }
};

var Button = React.createClass({
  mixins: [ColorMixin],

  render: function() {
    var theme = this.getLuminance(this.props.color) > 160 ? 'dark' : 'light';
    return (
      <div className={theme}>
        {this.props.children}
      </div>
    )
  }
});

Solution #

Put utility functions into regular JavaScript modules and import them. This also makes it easier to test them or use them outside of your components:

var getLuminance = require('../utils/getLuminance');

var Button = React.createClass({
  render: function() {
    var theme = getLuminance(this.props.color) > 160 ? 'dark' : 'light';
    return (
      <div className={theme}>
        {this.props.children}
      </div>
    )
  }
});

Other Use Cases #

Sometimes people use mixins to selectively add logging to lifecycle hooks in some components. In the future, we intend to provide an official DevTools API that would let you implement something similar without touching the components. However it’s still very much a work in progress. If you heavily depend on logging mixins for debugging, you might want to keep using those mixins for a little longer.

If you can’t accomplish something with a component, a higher-order component, or a utility module, it could be mean that React should provide this out of the box. File an issue to tell us about your use case for mixins, and we’ll help you consider alternatives or perhaps implement your feature request.

Mixins are not deprecated in the traditional sense. You can keep using them with React.createClass(), as we won’t be changing it further. Eventually, as ES6 classes gain more adoption and their usability problems in React are solved, we might split React.createClass() into a separate package because most people wouldn’t need it. Even in that case, your old mixins would keep working.

We believe that the alternatives above are better for the vast majority of cases, and we invite you to try writing React apps without using mixins.

Introducing React's Error Code System

July 11, 2016 by Keyan Zhang


Building a better developer experience has been one of the things that React deeply cares about, and a crucial part of it is to detect anti-patterns/potential errors early and provide helpful error messages when things (may) go wrong. However, most of these only exist in development mode; in production, we avoid having extra expensive assertions and sending down full error messages in order to reduce the number of bytes sent over the wire.

Prior to this release, we stripped out error messages at build-time and this is why you might have seen this message in production:

Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.

In order to make debugging in production easier, we're introducing an Error Code System in 15.2.0. We developed a gulp script that collects all of our invariant error messages and folds them to a JSON file, and at build-time Babel uses the JSON to rewrite our invariant calls in production to reference the corresponding error IDs. Now when things go wrong in production, the error that React throws will contain a URL with an error ID and relevant information. The URL will point you to a page in our documentation where the original error message gets reassembled.

While we hope you don't see errors often, you can see how it works here. This is what the same error from above will look like:

Minified React error #109; visit https://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Foo for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

We do this so that the developer experience is as good as possible, while also keeping the production bundle size as small as possible. This feature shouldn't require any changes on your side — use the min.js files in production or bundle your application code with process.env.NODE_ENV === 'production' and you should be good to go!

React v15.0.1

April 8, 2016 by Paul O’Shannessy


Yesterday afternoon we shipped v15.0.0 and quickly got some feedback about a couple of issues. We apologize for these problems and we've been working since then to make sure we get fixes into your hands as quickly as possible.

The first of these issues is related to the removal of an undocumented API. This API was added to enable JSX Spread Attributes in our JS compile tools (react-tools, JSXTransformer) before Object.assign was standard. When we stopped supporting these tools last year, we kept the API there to catch the longer tail of people using those tools. Meanwhile we moved to using Babel and encouraged others to do the same. Babel will typically compile the spread use to an _extends helper, which will use Object.assign. We did not properly research other compilation tools before deciding to remove the API in v15. Specifically, TypeScript and coffee-react are two popular packages using React.__spread, as well as reactify which still makes use react-tools. In order to make sure that code compiled with these tools is not broken, we will be restoring the React.__spread API and adding a warning. It will be removed in the future so if you maintain a project making using of it, we encourage you to compile to Object.assign directly or a similar helper function.

The second issue resulted in cursor position being lost in controlled inputs. We merged a pull request earlier this week to fix a separate regression from v0.14. Our goal was to target <option> elements but we ended up targeting all interactions with value properties. Unfortunately we didn't test it as thoroughly as we thought. We backed out the offending change and fixed the issue in different way which doesn't have the same problem.

We apologize if you installed 15.0.0 and have encountered these issues yourselves.

As usual, you can get install the react package via npm or download a browser bundle.

Changelog #

React #

  • Restore React.__spread API to unbreak code compiled with some tools making use of this undocumented API. It is now officially deprecated.
    @zpao in #6444

ReactDOM #

  • Fixed issue resulting in loss of cursor position in controlled inputs.
    @spicyj in #6449

React v15.0

April 7, 2016 by Dan Abramov


We would like to thank the React community for reporting issues and regressions in the release candidates on our issue tracker. Over the last few weeks we fixed those issues, and now, after two release candidates, we are excited to finally release the stable version of React 15.

As a reminder, we’re switching to major versions to indicate that we have been using React in production for a long time. This 15.0 release follows our previous 0.14 version and we’ll continue to follow semver like we’ve been doing since 2013. It’s also worth noting that we no longer actively support Internet Explorer 8. We believe React will work in its current form there but we will not be prioritizing any efforts to fix new issues that only affect IE8.

React 15 brings significant improvements to how we interact with the DOM:

  • We are now using document.createElement instead of setting innerHTML when mounting components. This allows us to get rid of the data-reactid attribute on every node and make the DOM lighter. Using document.createElement is also faster in modern browsers and fixes a number of edge cases related to SVG elements and running multiple copies of React on the same page.

  • Historically our support for SVG has been incomplete, and many tags and attributes were missing. We heard you, and in React 15 we added support for all the SVG attributes that are recognized by today’s browsers. If we missed any of the attributes you’d like to use, please let us know. As a bonus, thanks to using document.createElement, we no longer need to maintain a list of SVG tags, so any SVG tags that were previously unsupported should work just fine in React 15.

  • We received some amazing contributions from the community in this release, and we would like to highlight this pull request by Michael Wiencek in particular. Thanks to Michael’s work, React 15 no longer emits extra <span> nodes around the text, making the DOM output much cleaner. This was a longstanding annoyance for React users so it’s exciting to accept this as an outside contribution.

While this isn’t directly related to the release, we understand that in order to receive more community contributions like Michael’s, we need to communicate our goals and priorities more openly, and review pull requests more decisively. As a first step towards this, we started publishing React core team weekly meeting notes again. We also intend to introduce an RFC process inspired by Ember RFCs so external contributors can have more insight and influence in the future development of React. We will keep you updated about this on our blog.

We are also experimenting with a new changelog format in this post. Every change now links to the corresponding pull request and mentions the author. Let us know whether you find this useful!

Upgrade Guide #

As usual with major releases, React 15 will remove support for some of the patterns deprecated nine months ago in React 0.14. We know changes can be painful (the Facebook codebase has over 20,000 React components, and that’s not even counting React Native), so we always try to make changes gradually in order to minimize the pain.

If your code is free of warnings when running under React 0.14, upgrading should be easy. The bulk of changes in this release are actually behind the scenes, impacting the way that React interacts with the DOM. The other substantial change is that React now supports the full range of SVG elements and attributes. Beyond that we have a large number of incremental improvements and additional warnings aimed to aid developers. We’ve also laid some groundwork in the core to bring you some new capabilities in future releases.

See the changelog below for more details.

Installation #

We recommend using React from npm and using a tool like browserify or webpack to build your code into a single bundle. To install the two packages:

  • npm install --save react react-dom

Remember that by default, React runs extra checks and provides helpful warnings in development mode. When deploying your app, set the NODE_ENV environment variable to production to use the production build of React which does not include the development warnings and runs significantly faster.

If you can’t use npm yet, we provide pre-built browser builds for your convenience, which are also available in the react package on bower.

Changelog #

Major changes #

  • document.createElement is in and data-reactid is out #

    There were a number of large changes to our interactions with the DOM. One of the most noticeable changes is that we no longer set the data-reactid attribute for each DOM node. While this will make it more difficult to know if a website is using React, the advantage is that the DOM is much more lightweight. This change was made possible by us switching to use document.createElement on initial render. Previously we would generate a large string of HTML and then set node.innerHTML. At the time, this was decided to be faster than using document.createElement for the majority of cases and browsers that we supported. Browsers have continued to improve and so overwhelmingly this is no longer true. By using createElement we can make other parts of React faster. The ids were used to map back from events to the original React component, meaning we had to do a bunch of work on every event, even though we cached this data heavily. As we’ve all experienced, caching and in particularly invalidating caches, can be error prone and we saw many hard to reproduce issues over the years as a result. Now we can build up a direct mapping at render time since we already have a handle on the node.

    Note: data-reactid is still present for server-rendered content, however it is much smaller than before and is simply an auto-incrementing counter.

    @spicyj in #5205

  • No more extra <span>s #

    Another big change with our DOM interaction is how we render text blocks. Previously you may have noticed that React rendered a lot of extra <span>s. For example, in our most basic example on the home page we render <div>Hello {this.props.name}</div>, resulting in markup that contained 2 <span>s. Now we’ll render plain text nodes interspersed with comment nodes that are used for demarcation. This gives us the same ability to update individual pieces of text, without creating extra nested nodes. Very few people have depended on the actual markup generated here so it’s likely you are not impacted. However if you were targeting these <span>s in your CSS, you will need to adjust accordingly. You can always render them explicitly in your components.

    @mwiencek in #5753

  • Rendering null now uses comment nodes #

    We’ve also made use of these comment nodes to change what null renders to. Rendering to null was a feature we added in React 0.11 and was implemented by rendering <noscript> elements. By rendering to comment nodes now, there’s a chance some of your CSS will be targeting the wrong thing, specifically if you are making use of :nth-child selectors. React’s use of the <noscript> tag has always been considered an implementation detail of how React targets the DOM. We believe they are safe changes to make without going through a release with warnings detailing the subtle differences as they are details that should not be depended upon. Additionally, we have seen that these changes have improved React performance for many typical applications.

    @spicyj in #5451

  • Functional components can now return null too #

    We added support for defining stateless components as functions in React 0.14. However, React 0.14 still allowed you to define a class component without extending React.Component or using React.createClass(), so we couldn’t reliably tell if your component is a function or a class, and did not allow returning null from it. This issue is solved in React 15, and you can now return null from any component, whether it is a class or a function.

    @jimfb in #5884

  • Improved SVG support #

    All SVG tags are now fully supported. (Uncommon SVG tags are not present on the React.DOM element helper, but JSX and React.createElement work on all tag names.) All SVG attributes that are implemented by the browsers should be supported too. If you find any attributes that we have missed, please let us know in this issue.

    @zpao in #6243

Breaking changes #

  • No more extra <span>s #

    It’s worth calling out the DOM structure changes above again, in particular the change from <span>s. In the course of updating the Facebook codebase, we found a very small amount of code that was depending on the markup that React generated. Some of these cases were integration tests like WebDriver which were doing very specific XPath queries to target nodes. Others were simply tests using ReactDOM.renderToStaticMarkup and comparing markup. Again, there were a very small number of changes that had to be made, but we don’t want anybody to be blindsided. We encourage everybody to run their test suites when upgrading and consider alternative approaches when possible. One approach that will work for some cases is to explicitly use <span>s in your render method.

    @mwiencek in #5753

  • React.cloneElement() now resolves defaultProps #

    We fixed a bug in React.cloneElement() that some components may rely on. If some of the props received by cloneElement() are undefined, it used to return an element with undefined values for those props. In React 15, we’re changing it to be consistent with createElement(). Now any undefined props passed to cloneElement() are resolved to the corresponding component’s defaultProps. Only one of our 20,000 React components was negatively affected by this so we feel comfortable releasing this change without keeping the old behavior for another release cycle.

    @truongduy134 in #5997

  • ReactPerf.getLastMeasurements() is opaque #

    This change won’t affect applications but may break some third-party tools. We are revamping ReactPerf implementation and plan to release it during the 15.x cycle. The internal performance measurement format is subject to change so, for the time being, we consider the return value of ReactPerf.getLastMeasurements() an opaque data structure that should not be relied upon.

    @gaearon in #6286

  • Removed deprecations #

    These deprecations were introduced nine months ago in v0.14 with a warning and are removed:

    • Deprecated APIs are removed from the React top-level export: findDOMNode, render, renderToString, renderToStaticMarkup, and unmountComponentAtNode. As a reminder, they are now available on ReactDOM and ReactDOMServer.
      @jimfb in #5832
    • Deprecated addons are removed: batchedUpdates and cloneWithProps.
      @jimfb in #5859, @zpao in #6016
    • Deprecated component instance methods are removed: setProps, replaceProps, and getDOMNode.
      @jimfb in #5570
    • Deprecated CommonJS react/addons entry point is removed. As a reminder, you should use separate react-addons-* packages instead. This only applies if you use the CommonJS builds.
      @gaearon in #6285
    • Passing children to void elements like <input> was deprecated, and now throws an error.
      @jonhester in #3372
    • React-specific properties on DOM refs (e.g. this.refs.div.props) were deprecated, and are removed now.
      @jimfb in #5495

New deprecations, introduced with a warning #

Each of these changes will continue to work as before with a new warning until the release of React 16 so you can upgrade your code gradually.

  • LinkedStateMixin and valueLink are now deprecated due to very low popularity. If you need this, you can use a wrapper component that implements the same behavior: react-linked-input.
    @jimfb in #6127

  • Future versions of React will treat <input value={null}> as a request to clear the input. However, React 0.14 has been ignoring value={null}. React 15 warns you on a null input value and offers you to clarify your intention. To fix the warning, you may explicitly pass an empty string to clear a controlled input, or pass undefined to make the input uncontrolled.
    @antoaravinth in #5048

  • ReactPerf.printDOM() was renamed to ReactPerf.printOperations(), and ReactPerf.getMeasurementsSummaryMap() was renamed to ReactPerf.getWasted().
    @gaearon in #6287

New helpful warnings #

  • If you use a minified copy of the development build, React DOM kindly encourages you to use the faster production build instead.
    @spicyj in #5083

  • React DOM: When specifying a unit-less CSS value as a string, a future version will not add px automatically. This version now warns in this case (ex: writing style={{width: '300'}}. Unitless number values like width: 300 are unchanged.
    @pluma in #5140

  • Synthetic Events will now warn when setting and accessing properties (which will not get cleared appropriately), as well as warn on access after an event has been returned to the pool.
    @kentcdodds in #5940 and @koba04 in #5947

  • Elements will now warn when attempting to read ref and key from the props.
    @prometheansacrifice in #5744

  • React will now warn if you pass a different props object to super() in the constructor.
    @prometheansacrifice in #5346

  • React will now warn if you call setState() inside getChildContext().
    @raineroviir in #6121

  • React DOM now attempts to warn for mistyped event handlers on DOM elements, such as onclick which should be onClick.
    @ali in #5361

  • React DOM now warns about NaN values in style.
    @jontewks in #5811

  • React DOM now warns if you specify both value and defaultValue for an input.
    @mgmcdermott in #5823

  • React DOM now warns if an input switches between being controlled and uncontrolled.
    @TheBlasfem in #5864

  • React DOM now warns if you specify onFocusIn or onFocusOut handlers as they are unnecessary in React.
    @jontewks in #6296

  • React now prints a descriptive error message when you pass an invalid callback as the last argument to ReactDOM.render(), this.setState(), or this.forceUpdate().
    @conorhastings in #5193 and @gaearon in #6310

  • Add-Ons: TestUtils.Simulate() now prints a helpful message if you attempt to use it with shallow rendering.
    @conorhastings in #5358

  • PropTypes: arrayOf() and objectOf() provide better error messages for invalid arguments.
    @chicoxyzzy in #5390

Notable bug fixes #

  • Fixed multiple small memory leaks.
    @spicyj in #4983 and @victor-homyakov in #6309

  • Input events are handled more reliably in IE 10 and IE 11; spurious events no longer fire when using a placeholder.
    @jquense in #4051

  • The componentWillReceiveProps() lifecycle method is now consistently called when context changes.
    @milesj in #5787

  • React.cloneElement() doesn’t append slash to an existing key when used inside React.Children.map().
    @ianobermiller in #5892

  • React DOM now supports the cite and profile HTML attributes.
    @AprilArcus in #6094 and @saiichihashimoto in #6032

  • React DOM now supports cssFloat, gridRow and gridColumn CSS properties.
    @stevenvachon in #6133 and @mnordick in #4779

  • React DOM now correctly handles borderImageOutset, borderImageWidth, borderImageSlice, floodOpacity, strokeDasharray, and strokeMiterlimit as unitless CSS properties.
    @rofrischmann in #6210 and #6270

  • React DOM now supports the onAnimationStart, onAnimationEnd, onAnimationIteration, onTransitionEnd, and onInvalid events. Support for onLoad has been added to object elements.
    @tomduncalf in #5187, @milesj in #6005, and @ara4n in #5781

  • React DOM now defaults to using DOM attributes instead of properties, which fixes a few edge case bugs. Additionally the nullification of values (ex: href={null}) now results in the forceful removal, no longer trying to set to the default value used by browsers in the absence of a value.
    @syranide in #1510

  • React DOM does not mistakingly coerce children to strings for Web Components.
    @jimfb in #5093

  • React DOM now correctly normalizes SVG <use> events.
    @edmellum in #5720

  • React DOM does not throw if a <select> is unmounted while its onChange handler is executing.
    @sambev in #6028

  • React DOM does not throw in Windows 8 apps.
    @Andrew8xx8 in #6063

  • React DOM does not throw when asynchronously unmounting a child with a ref.
    @yiminghe in #6095

  • React DOM no longer forces synchronous layout because of scroll position tracking.
    @syranide in #2271

  • Object.is is used in a number of places to compare values, which leads to fewer false positives, especially involving NaN. In particular, this affects the shallowCompare add-on.
    @chicoxyzzy in #6132

  • Add-Ons: ReactPerf no longer instruments adding or removing an event listener because they don’t really touch the DOM due to event delegation.
    @antoaravinth in #5209

 Other improvements #

  • React now uses loose-envify instead of envify so it installs fewer transitive dependencies.
    @qerub in #6303

  • Shallow renderer now exposes getMountedInstance().
    @glenjamin in #4918

  • Shallow renderer now returns the rendered output from render().
    @simonewebdesign in #5411

  • React no longer depends on ES5 shams for Object.create and Object.freeze in older environments. It still, however, requires ES5 shims in those environments.
    @dgreensp in #4959

  • React DOM now allows data- attributes with names that start with numbers.
    @nLight in #5216

  • React DOM adds a new suppressContentEditableWarning prop for components like Draft.js that intentionally manage contentEditable children with React.
    @mxstbr in #6112

  • React improves the performance for createClass() on complex specs.
    @spicyj in #5550

React v0.14.8

March 29, 2016 by Dan Abramov


We have already released two release candidates for React 15, and the final version is coming soon.

However Ian Christian Myers discovered a memory leak related to server rendering in React 0.14 and contributed a fix. While this memory leak has already been fixed in a different way in the React 15 release candidates, we decided to cut another 0.14 release that contains just this fix.

The release is now available for download:

We've also published version 0.14.8 of the react, react-dom, and addons packages on npm and the react package on bower.


Changelog #

React #

  • Fixed memory leak when rendering on the server