Debouncing with Hooks
As we have seen in the previous section, when we press undo it undoes a single character at a time. Sometimes, we do not want to store every change in our undo history. To avoid storing every change, we need to implement debouncing, which means that the function that stores the content
to the history state is only called after there are no changes for a certain amount of time.
The use-debounce
library provides a Debounce Hook, which can be used, as follows, for simple values:
const [text, setText] = useState('')
const [value] = useDebounce(text, 1000)
Now, if we change the text via setText
, the text
value will be updated instantly, but the value
variable will only be updated after 1000 ms (1 second).
However, for our use case, this is not enough. We are going to need debounced callbacks in order to implement debouncing in combination with the History State Hook. Thankfully, the use-debounce
library also provides the Debounced Callback...