Example of useDelay() Custom Hook in React.js

Example of useDelay() Custom Hook in React.js

The useDelay hook lets you wait a bit before running a function. Here's how to make it:

import { useEffect, useRef } from 'react';

const useDelay = (callback, delay) => {
  const callbackRef = useRef();

  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (callbackRef.current) {
    }, delay);

    return () => clearTimeout(timer);
  }, [delay]);

export default useDelay;

Now, let's see how you can use this custom hook in a component:

import React from 'react';
import useDelay from './useDelay'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  const handleClick = () => {
    console.log('Button clicked!');

  // Execute handleClick after a delay of 2000 milliseconds (2 seconds)
  useDelay(handleClick, 2000);

  return (
      <h1>useDelay Hook Example</h1>
      <button>Click me!</button>

export default MyComponent;

In this example:

  • We define the MyComponent functional component.

  • We define a handleClick function that logs a message to the console when called.

  • We use the useDelay hook to delay the execution of the handleClick function by 2000 milliseconds (2 seconds).

  • When the component mounts, the handleClick function will be executed after the specified delay.

This hook is helpful when you need to delay actions, like displaying a notification after some time or starting an event later.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!