I'm trying to debounce sending a Redux Action from an input change in React.
const debouncedSubmit = debounce(() => dispatch(new TaskAnswerSubmit({index: props.index, text: answer})), 1000)
function onChange(e){
setAnswer(e.target.value)
debouncedSubmit()
}
This is delaying sending the actions, but still sending one for every keypress. I want to wait a second after the typing finishes before sending the action just once.
What am I doing wrong here?
I'm trying to debounce sending a Redux Action from an input change in React.
const debouncedSubmit = debounce(() => dispatch(new TaskAnswerSubmit({index: props.index, text: answer})), 1000)
function onChange(e){
setAnswer(e.target.value)
debouncedSubmit()
}
This is delaying sending the actions, but still sending one for every keypress. I want to wait a second after the typing finishes before sending the action just once.
What am I doing wrong here?
Share Improve this question asked Mar 3, 2020 at 23:48 beekbeek 3,7469 gold badges40 silver badges100 bronze badges2 Answers
Reset to default 11I believe what's happening here is that each key press causes a re-render, and during each render it's creating a new debouncedSubmit
function, and each of those is firing. Try using React's useCallback
method to memoize the function so it's not recreated on re-renders:
const debouncedSubmit = useCallback(debounce(() => dispatch(new TaskAnswerSubmit({index: props.index, text: answer})), 1000), []);
I think you need to throttle.
This is an answer from a previously asked question about the difference between throttle and debounce Difference Between throttling and debouncing a function:
Throttling will delay executing a function. It will reduce the notifications of an event that fires multiple times.
Debouncing will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.