top of page
Logo der Online Agentur mdwp

Mixins

Mixins in React JS are a way to share functionality between multiple components. They are a chunk of code encapsulating certain behavior that is shared across multiple components. For example, timers, scrolling functionality, or data fetching. They enable the code reuse in a different way than traditional inheritance.

However, please note that mixins are getting fade out with the new ES6 class syntax in React. Instead, higher order components or functions, context, and new Hook system are used.

Here, we demonstrate a basic mixin creation:

```javascript
var SetIntervalMixin = {
componentWillMount: function() {
this.intervals = [];
},
setInterval: function() {
this.intervals.push(setInterval.apply(null, arguments));
},
componentWillUnmount: function() {
this.intervals.forEach(clearInterval);
}
};

var TickTock = React.createClass({
mixins: [SetIntervalMixin], // Use the mixin
getInitialState: function() {
return {seconds: 0};
},
componentDidMount: function() {
this.setInterval(this.tick, 1000); // Call a method on the mixin
},
tick: function() {
this.setState({seconds: this.state.seconds + 1});
},
render: function() {
return (
<p>
Been running for {this.state.seconds} seconds.
</p>
);
}
});
```
In this code, SetIntervalMixin is our mixin that contains common functionality for any component need to set interval. The Interval IDs stored in this.intervals in the mixin, we don't have to worry about leaking memory. It's all cleaned up for us when the component is unmounted.

The mixin becomes a part of the component class which is then used to create the component instance (TickTock), which makes it possible to call this.setInterval method defined in the mixin from the scope of the component.

bottom of page