3

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?

beek
  • 3,522
  • 8
  • 33
  • 86

2 Answers2

8

I 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), []);
beek
  • 3,522
  • 8
  • 33
  • 86
Jayce444
  • 8,725
  • 3
  • 27
  • 43
0

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.

mosmk
  • 403
  • 2
  • 7