Skip to content

Instantly share code, notes, and snippets.

@ericchernuka
Last active March 21, 2017 21:18
Show Gist options
  • Save ericchernuka/683bd1deaed932173ad2fa86a90b2f54 to your computer and use it in GitHub Desktop.
Save ericchernuka/683bd1deaed932173ad2fa86a90b2f54 to your computer and use it in GitHub Desktop.
React Interval Component
import React, { Component } from 'react';
/**
* Declarative approach to setInterval
*/
class ReactInterval extends Component {
static propTypes = {
enabled: React.PropTypes.bool,
interval: React.PropTypes.number, // interval time in ms
onInterval: React.PropTypes.func.isRequired
}
static defaultProps = {
enabled: false,
interval: 1000
}
componentDidMount() {
if (this.props.enabled) {
this.start()
}
}
componentDidUpdate(prevProps) {
if (this.props.enabled !== prevProps.enabled) {
if (this.props.enabled) {
this.start()
} else {
clearInterval(this.interval)
}
}
}
componentWillUnmount() {
clearInterval(this.interval)
}
start = () => {
this.interval = setInterval(this.tick, this.props.interval)
}
tick = () => {
this.props.onInterval && this.props.onInterval()
}
render() {
return this.props.children || null
}
}
export default ReactInterval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment