← back to the blog

React mixins, Why use mixins?

Posted on January 23rd, 2019 in JavaScript by George

Mixins are basically a collection of functions you may share on different components.

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?

First of all, the first reason for which I would avoid to use mixins is that you ar are bound to use React.createClass() or create-class-module, ES6 classes are not compatible with React mixins. 

If you are not familiar with how mixins look like, take a look at the following example:


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

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

  // ...


 Mixins are often used with a type of Flux Store where you have to create a subscription in componentDidMount and remove it in componentWillUnmount where the change handles is going to use this.setState().

There are few available tools there like  (Fluxxor http://fluxxor.com/) which will deal automatically with the processes described above for you.  If you base your application to depend on a Store management tool which is based on mixins then you are forced to stick for with ES5 classes until the end.