Skip to content

Instantly share code, notes, and snippets.

@laytong
Last active December 18, 2021 06:16
Show Gist options
  • Save laytong/e2aeecf32283c3a1ab6edf8e38a78903 to your computer and use it in GitHub Desktop.
Save laytong/e2aeecf32283c3a1ab6edf8e38a78903 to your computer and use it in GitHub Desktop.
How to debounce your inputs for super fast react/redux components
import React, {Component, PropTypes} from 'react';
class BadInputComponent extends Component {
static propTypes = {
text = PropTypes.string.isRequired,
updateText = PropTypes.func.isRequired,
};
render() {
return (
<input onChange={this.handleTextChange} value={this.state.text} />
);
}
handleTextChange = (e) => {
this.props.updateText(e.target.value)
};
}
export default BadInputComponent;
import React, {Component, PropTypes} from 'react';
import debounce from 'lodash/debounce';
class DebouncedInputComponent extends Component {
static propTypes = {
text = PropTypes.string.isRequired,
updateText = PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
text: '',
};
}
componentDidMount() {
this.sendTextChange = debounce(this.sendTextChange, 500);
this.setState({text:this.props.text});
}
render() {
return (
<input onChange={this.handleTextChange} value={this.state.text} />
);
}
handleTextChange = (e) => {
this.setState({text: e.target.value});
this.sendTextChange(e.target.value.trim())
};
sendTextChange = (text) => {
this.props.updateText(text);
};
}
export default DebouncedInputComponent;
@hansena
Copy link

hansena commented Dec 7, 2020

Same but w/ hooks...

import React, { useState } from "react";
import debounce from "lodash/debounce";

export const debounceTextbox = (Component, timeout = 500) => ({ onChange, value, ...props }) => {
	const [debouncedValue, setValue] = useState(value);
	const handleTextChange = (e) => {
		setValue(e.target.value);
		sendChange(e);
	};
	const sendTextChange = debounce((newValue) => onChange(newValue), timeout);

	return <Component {...props} onChange={handleTextChange} value={debouncedValue} />;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment