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 our content to the undo history is only called after a certain amount of time.

The use-debounce library provides the useDebounce 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 use-undo. The use-debounce library also provides the useDebouncedCallback Hook, which can be used as follows:

const [ text, setText ] = useState('')
const [ debouncedSet, cancelDebounce ] = useDebouncedCallback(
(value) => setText(value),
1000
)

Now, if we call debouncedSet('text'), the text value will be updated after 1000 ms (1 second). If debouncedSet is called multiple times, the timeout will get reset every time, so that only after 1000 ms of no further calls to the debouncedSet function, the setText function will be called. Next, we are going to move on to implementing debouncing in our post editor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.175.182