beek
beek

Reputation: 3750

Lodash debounce firing every change

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?

Upvotes: 3

Views: 3201

Answers (2)

Jayce444
Jayce444

Reputation: 9063

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), []);

Upvotes: 11

mosmk
mosmk

Reputation: 413

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.

Upvotes: 0

Related Questions