React JS

The most useful React custom hook! (Part-1)

April 12, 2024
5 Min
Custom Hook

Hello world!

Have you ever spent half-an-hour on filling out a form only to realize that it was full of errors after hitting the submit button? I did it, and as a developer — It was “OMG! seriously!” to me. I wonder how would a regular user feel like.

How smooth would it have been had it shown the error the moment I finished typing? It would’ve been a cakewalk to fill and submit the form and you needn’t have spent 5 mins reading this article today.

In this brief article, we’ll skim through two of the important advanced React concepts ‘Debouncing and React custom hooks’. Two birds in one shot, haha!

Let’s start with understanding what’s debouncing. Debouncing is a technique used to eliminate unwanted function calls on each user input. Yea, yea, yea, I know it doesn’t make a lot of sense at the moment, but stay with me.

Consider an instance where you searched for something on YouTube, you’ll get the search results as soon as you stop typing. So what’s happening in the background? It is obvious that the front end fires an API call to the back end to query the results. But if you fire an API on every letter you type, how many API calls will it take? Let’s take a rough estimate — If I search for “Shape of you by Ed Sheeran” that’s 27 API calls. Assuming, at the least that there are a million users per day, it’s 27 million API calls to the back-end.

Now, if I can manage to wait until the user stops typing and then make an API call, it’s one API call per user and the total API calls will fall down to 1 million per day, except for the fact that the actual number of users is significantly higher.

This is where we use Debouncing. We write a debounce function that will have an internal timer (let’s say 3–5 seconds) which will trigger a call-back function once the timer is timed out. This is straightforward, but the catch here is that we will also have a condition that says, If the timer is already active, it will be reset, and a new timer will begin. This new timer will wait for a specified time, giving the user the opportunity to type the next character. If the user doesn't type anything within this specified time, the timer will expire, and the API call will be initiated. That's it!

Now read this again, Debouncing is a technique to eliminate unwanted function calls on each user input. Makes more sense this time, right? You have now learned what is the logic behind it. This is not just constrained to API, it works wonders with APIs, validations, window resizing, and any other functions!

Let’s take a look at the code snippet

let debounceTimer;

 const debounce = (callback, args, delay) => {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
      debounceTimer = null;
    }

    debounceTimer = (
      setTimeout(() => {
        callback(args);
      }, delay)
    );
  };

In the above code snippet, we are creating a debounce function that takes

1) The callback function

2) Arguments for the callback

3) The delay until which the function should wait to be called.

As we read before, we clear the timer if it already exists and create a new timer every time the debounce function is triggered.

Here’s how we can call it

const DEBOUNCE_DELAY = 3000 //milliseconds 

  // handle input field change
  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    debounce(validateFormData, event, DEBOUNCE_DELAY);
  };

And that’s it, it’s that simple!!! You can now use the above code snippets to implement debouncing in your project and optimize it for unwanted function calls.

Though it’s pretty useful for optimization, there is one drawback in this i.e. you have to implement the function in every single file.

To solve this and optimize it further, we will learn about React Custom hooks and extract our debounce function into a new custom hook to make it a super cool globally reusable function.

Stay tuned for more!

Happy hacking…

Read part-2 of the most useful React custom hook here

Author
Renuka Prasad Photo
Renuka Prasad
Software Developer
Disclaimer: This article outline is created by Humans, content is written by AI and the final article is reviewed & edited by a CodeWalnut engineer.
Next-JS Logo
Kickstart your
React JS
project

Experience coding prowess firsthand. Choose CodeWalnut to build a prototype within a week and make your choice with confidence.

Book a Meeting
Vercel Logo
Kickstart your
React JS
project

Accelerate your web app vision with CodeWalnut. In just a week, we'll shape your idea into a polished prototype, powered by Vercel. Ready to make it real? Choose us with confidence!

Book a Meeting
Heroku Logo
Kickstart your
Heroku
project

Dreaming of a powerful web app on Heroku? Let CodeWalnut bring it to life in just one week. Take the leap and trust us to deliver with confidence!

Book a Meeting

Related posts

Partner with CodeWalnut to drive your digital growth!
Tell us about yourself and we will show you how technology can help drive business growth.
Thank you for your interest in CodeWalnut.Our digital expert will reach you within 24-48 hours.
Oops! Something went wrong while submitting the form.