Instead of shouting Mixins are harmful, let's create a component that is using them and look at what the issues are. Mixins are deprecated, so the first step is finding a way to use them. It turns out that they still live in a legacy way of creating React class components. Previously, instead of ES6 classes, there was a special function called createReactClass. In one of the major releases, the function was removed from the React library and is now available in a separate library called 'create-react-class':
// Chapter 2_View patterns/Example 12/App.js ... import createReactClass from 'create-react-class';
const LoggerMixin = { componentDidMount: function() { // uses lifecycle method to log console.log('Component has been rendered successfully!'); } }; export default createReactClass({ mixins: [LoggerMixin], render: function() { return ( <View> <Text>Some text in a component with mixin.</Text> </View> ); } });
Here, we create LoggerMixin, which is taking care of logging the necessary information. In this simple example, it's just information regarding that component that has been rendered, but it could be easily extended further.
In this example, we used componentDidMount, which is one of the component life cycle hooks. These can be used in ES6 classes, too. Please check out the official documentation for insights about the other methods: https://reactjs.org/docs/react-component.html#the-component-lifecycle.
In case you need more loggers, you can mix them into a single component by using a comma:
... mixins: [LoggerMixin, LoggerMixin2], ...
This is a book on patterns, so it is crucial to stop here and look at the createReactClass function.
Why has it been deprecated? The answer is actually pretty simple. The React Team prefers explicit APIs over implicit APIs. The CreateReactClass function is another implicit abstraction that hides implementation details from you. Instead of adding a new function, it is better to use the standard way: ES6 classes. ES6 classes have their own cons, but that is another topic entirely. Additionally, you may use classes in other languages that are built on top of ECMAScript, for instance, TypeScript. This is a huge advantage, especially nowadays, with TypeScript going mainstream.
To find out more on this thought process, I recommend that you watch a great talk from Sebastian Markb?ge called Minimal API Surface Area. It was originally delivered at JSConf EU in 2014, and can be found at https://www.youtube.com/watch?v=4anAwXYqLG8.