Debouncing + React

January 02, 2022

JavaScript
TypeScript
React

Debouncing is a technique to control how many times we allow a function to be executed over time. For today's article, we’ll reference a search bar since it's a common use case for this scenario when your'e trying to manage a large data set containing thousands of nodes across your server(s).

The lodash docs give a great definition:

...function that delays invoking func until after wait ms have elapsed since the last time the denounced function was invoked


Use Case

In the Fullcourt app, we currently use debounce to restrict the number of calls we make to our server. Imagine having a list of Cities and with every event change we not only shake our tree, but we’re making accessive calls to query a city/or cities, and that can cause bad performance for our users.


Approach

We can create a custom hook and import it into our search module. The question is do you really need to do this? Yes! Yes, you do if you want to save money on your car insurance by switching to... I’m joking lol. Seriously, yes.

Our custom hook will look like this useDebounced<T>(f: func, w: number, o?: Object) f take in the function and w will allow our hook to be configurable, and o will be our options.

Let’s Implement it below:

1// for our options that contains flags
2// lets iterate through the keys to create a type
3// we don't use but I figured it be fun to make this type
4
5 type OptionsFlags<T> = {
6 [Property in keyof T]: boolean
7 }
8
9 type Flags = {
10 leading?: boolean
11 trailing?: boolean
12}
13
14type DebounceFlags = OptionsFlags<Flags>
15
16type MaxWaitOption<T> = {
17 [key: keyof T]: number
18}
19
20type MaxWaitProp = {
21 maxWait?: number
22}
23
24type MaxWait = MaxWaitOptions<MaxWaitProp>
25
26// intersect our props
27type Options = DebounceFlags & MaxWait
28
29interface DebounceProps = {
30 func: () => void
31 wait: number
32 options?: Options
33}
34
35function useDebounced({ func, wait }: DebounceProps) {
36 let [debouncedValue, setDebouncedValue] = useState(func)
37
38 useEffect(() => {
39 let timeOutId = setTimeout(() => {
40 setDebouncedValue(func)
41 }, wait)
42
43 // cleanup
44 return () => {
45 clearTimeout(timeoutId)
46 }
47 }, [func, wait])
48
49 return debouncedValue
50}
51
52module.exports = { useDebounced }

Usage

Now we can just drop it into our Search Component and call it a day. One thing you will notice is that we’re no longer causing a bottleneck to our server, and no matter how many characters we type into our search the useDebounced hook will only fire wait ms after the user is done typing.

I’m only implementing pseudo logic for our use case. This will give you a general idea of how to add this piece to your puzzle

1import React from 'react';
2import { useDebounced } from '../src/hooks/';
3
4const Example: React.FC = ({}) => {
5 const [query, setQuery] = useState < string > '';
6 const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
7 setQuery(e?.target?.value);
8 };
9
10 // we call our custom hook :)
11 const debouncedOnChange = useDebounced(onChange, 500);
12
13 {
14 /* semantic HTML FTW!!! */
15 }
16 return (
17 <div class="search-container">
18 <form action="#" method="get">
19 <label forHTML={query}>
20 Search
21 {/* use it on our onChange prop */}
22 <input
23 type="text"
24 name={query}
25 placeholder="Search for a City..."
26 onChange={debouncedOnChange}
27 />
28 </label>
29 {/*other fun stuff below*/}
30 </form>
31 </div>
32 );
33};

Conclusion

Today we learned about debouncing and the problems it can resolve for many users who are experiencing performance issues. Debouncing is a common technique for handling events in a sophisticated way. We can target events to help us avoid doing extra work and allow us to control when we want to execute our function.

Resources:

I hope you enjoyed reading the article :) Happy New Year!!!


my shoe
I’m Marlon but you can call me Mars. Software Engineer. Music lover. Bay Area Native. Feel free to Contact me.
  • implement promisify