Since React mixins are now deprecated, here's an example of a higher order component that wraps another component to give the same functionality as described in the accepted answer. It neatly cleans up any remaining timeouts on unmount, and gives the child component an API to manage this via props.
This uses ES6 classes and component composition which is the recommended way to replace mixins in 2017.
In Timeout.jsx
import React, { Component } from 'react';
const Timeout = Composition => class _Timeout extends Component {
constructor(props) {
super(props);
}
componentWillMount () {
this.timeouts = [];
}
setTimeout () {
this.timeouts.push(setTimeout.apply(null, arguments));
}
clearTimeouts () {
this.timeouts.forEach(clearTimeout);
}
componentWillUnmount () {
this.clearTimeouts();
}
render () {
const { timeouts, setTimeout, clearTimeouts } = this;
return <Composition
timeouts={timeouts}
setTimeout={setTimeout}
clearTimeouts={clearTimeouts}
{ ...this.props } />
}
}
export default Timeout;
In MyComponent.jsx
import React, { Component } from 'react';
import Timeout from './Timeout';
class MyComponent extends Component {
constructor(props) {
super(props)
}
componentDidMount () {
// You can access methods of Timeout as they
// were passed down as props.
this.props.setTimeout(() => {
console.log("Hey! I'm timing out!")
}, 1000)
}
render () {
return <span>Hello, world!</span>
}
}
// Pass your component to Timeout to create the magic.
export default Timeout(MyComponent);
clearTimeoutwill work assuming you store the timer id.