-
-
Save xamedow/8afe2ccafefc237d4184f1ec35c26e41 to your computer and use it in GitHub Desktop.
How to debounce your inputs for super fast react/redux components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment