I need the state to change to maintain the string the user is typing. However I want to delay an action until the user stops typing. But I can\'t quite place my finger on how to
You can debounce on the onChange event (if the user is typing the onchange event will not execute)
Warning - Keep in mind that creating functions on render is a bad practice. I did it in order to illustrate the solution. A more safe solution is to use a class Component that creates the debounced handler on its constructor.
class DebouncedInput extends React.Component {
constructor() {
super();
// Creating the debouncedOnChange to avoid performance issues
this._debouncedOnChange = _.debounce(
this.props.onChange,
this.props.delay
);
}
render () {
const { onChange, delay, ...rest } = this.props;
return (
)
}
}
Example below
function DebouncedInput (props) {
const { onChange, delay = 300, ...rest } = props;
return (
)
}
function App() {
return (
console.log('changing')}
/>
)
}
ReactDOM.render(
,
document.querySelector('#app')
);
JS Bin