React JS

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

September 27, 2024
5 Min
Custom Hook

The return of Hello world!!

Hey fellow developer, I’m back to complete the incomplete, the sequel of the most useful React custom hook

Previously, we learned about the concept of debouncing and its implementation (...can’t recall what I’m talking about? You might have probably missed part 1, read it here)

In this sequel, let’s dive into detail about custom hooks and how to globally extract our debouncing function. By the end of this blog, you’ll be able to implement your own React custom hooks and debounce using custom hooks. Just with 10 mins of coding, you’ll realize this is not as complicated as it may seem.

We now know that “Debouncing is a technique used to eliminate unwanted function calls on each user input”, but implementing it locally in each and every component results in code duplication, eats away your productivity, and also makes it painful to maintain your code. Arghhhhh!

The good news is… we have a ready solution. Implement it globally using a custom hook and call it in every file. In this blog, I’ll show you exactly how to do it.

To get there, we must first learn about custom hooks in React.

Let’s go…

What is a React custom hook?

Well you are already aware that we use react hooks for state management. The most common ones are useState, useEffect, and useContext to begin with. But what if you want a new hook that does a specific task that you can use in any component with all the benefits of the built-in hooks?

This is where React custom hooks come into the picture. React offers us the flexibility to write hooks on our own which can leverage its existing hooks to create a new one that performs any task you want it to. This is nothing but a custom hook.

I love how easy it is to understand this. A custom hook is a new and fully customizable React hook”, and that’s it. No ifs, no buts, and no lengthy explanations needed (Remember I said easy-peasy?)


When and why to use a custom hook?

Pretty straightforward, you can use this “When you want to share stateful logic between two components”.

Let’s go back to the API example from the previous blog, let’s say you want to call the same API in two different components and store the response data in a local state, rather than writing two useEffects in two different components, you can create a custom hook that does the API call for you, stores the response in a state and returns the state.

You can later call the custom hook in your component and Baammm!! You have the response data in both components without any duplicate code.

Observe what we are doing here, we are “sharing the state” between two components. This is a more efficient way than prop-drilling or bombarding our global context with useEffect callbacks.

How to create a custom hook?

Along with the React hook rules, there is one die-hard rule you MUST follow while creating a custom hook, viz.

A custom hook must start with the word “use” followed by a Pascal cased name.

Short exercise: Based on the above rule, can you guess what would be the name of our debounce custom hook?

Take a few seconds to think…

Bingo! It is “useDebounce”. Note how it starts with “use” and is followed by a Pascal case name “Debounce”. A custom hook is a regular function that starts with the keyword “use” which may call other hooks internally if needed and returns a state.

This is everything you need to know to write your own custom hook! Why wait any further? Let’s implement it right away.

The most useful React custom hook: useDebounce

Here is our existing debounce function

let debounceTimer;

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

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

We can create a file inside the utils folder and call it useDebouce.ts/tsx and refactor our existing debounce function into a custom hook

import { useState } from "react";

export function useDebounce(callback: Function, delay: number){
  const [debounceTimer, setDebounceTimer] = useState<null | NodeJS.Timer>(null);

  const debounce = (...args: any) => {
    if (debounceTimer) {
    clearTimeout(debounceTimer);
  }

  setDebounceTimer(
    setTimeout(() => {
      callback(...args):
    }, delay)
   );
  };

return debounce;
}

We are converting our timer into a state and returning the debounce function. This custom hook accepts a callback function and a delay time and debounces the callback function.

All set now! We implemented a global debouncing function that can be called in any component throughout the project.

The last step is to simply call the custom hook and use the callback function it provides.

const debounce = useDebounce(validateFormData, DEBOUNCE_DELAY);

const handleFormChange = (event: ChangeEvent<HTMLInputElement>) => {
debounce(event.target.name, event.target.value); // the arguments for the validateFormData callback function goes here
};

Bravo! you are now ready to debounce like a pro!

We’d love to hear from you! Do try it out and let us know if it helped (also, flaunt what you’ve learned to your fellow developers; because, as they say, sharing is caring xD)

Happy hacking…

Want help with your react app?

Get in touch - Our team has developed scalable solutions for enterprises and has a Crunch rating of 4.9⭐.

Contact us
Blog CTA Banner
Author
Renuka Prasad
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
Download 👑Premium Template
Contact Us
Red Curved Arrow
Download Free Template

Open Source Java + React Code with API and Database Configuration

Get Code
Red Curved Arrow
Request Your 👑Premium Template
Get It Now
Red Curved Arrow

Related posts

You are just one step away!

Enter your Email to receive free template developed by CodeWalnut Experts

Thank you! Your template has been sent Successfully!

Before you rush to your inbox, Do you know CodeWalnut offers free consultation?
Contact Us
Oops! Something went wrong while submitting the form.
You are just one step away!

Enter your Email to receive free template developed by CodeWalnut Experts.

Thank you! Your template has been sent Successfully!

Before you rush to your inbox, Do you know CodeWalnut offers free consultation?
Contact Us
Oops! Something went wrong while submitting the form.
You are just one step away!

Enter your email to receive the PR checklist prepared by CodeWalnut experts.

Thank you! Your PR Checklist has been sent Successfully!

Before you rush to your inbox, Do you know CodeWalnut offers free consultation?
Contact Us
Oops! Something went wrong while submitting the form.
Need help with building your next application?
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
What best describes you?
Beginner Programmer
Tech Manager
Enterprise IT Leader
Here are some useful resources for you
A boilerplate for React + Java
PR checklist to control code quality
Download Free Template
Open Source Java + React Code with API and Database Configuration
Download now
Here are some useful resources for you
React-Java Boilerplate
A boilerplate for React + Java
PR checklist to control code quality

Book a 15 min session to build your bulletproof development lifecycle

Book a meeting
Nattu
Nattu, Co Founder
Need help with building your next application?
Yes! Show me how