Skip to content

Instantly share code, notes, and snippets.

@TonyDotDev
Created February 22, 2020 20:38
Show Gist options
  • Save TonyDotDev/bccab47ef4806f31ed9830e9232ff819 to your computer and use it in GitHub Desktop.
Save TonyDotDev/bccab47ef4806f31ed9830e9232ff819 to your computer and use it in GitHub Desktop.
A higher order component for debouncing function calls.
import React, { Component } from "react";
function withDebounce(WrappedComponent) {
return class extends Component {
constructor(props) {
super(props);
this.timeout = null;
this.debounce = this.debounce.bind(this);
}
debounce(fn, time) {
if (this.timeout) clearTimeout(this.timeout);
this.timeout = setTimeout(fn, time);
}
render() {
return <WrappedComponent debounce={this.debounce} {...this.props} />;
}
};
}
export default withDebounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment