Example of useDebounce() Custom hook in React.js

Example of useDebounce() Custom hook in React.js

Here's how to make a useDebounce hook in React, which lets you wait before running a function:

import { useState, useEffect } from 'react';

const useDebounce = (value, delay) => {
  // State to hold the debounced value
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    // Update debounced value after delay
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    // Cleanup function to clear timeout on value change
    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
};

export default useDebounce;

You can use this useDebounce hook in your components to debounce the execution of a function or the handling of a value change. Here's how you can use it:

import React, { useState } from 'react';
import useDebounce from './useDebounce'; // Assuming you've placed the hook in a separate file

const MyComponent = () => {
  // State to hold input value
  const [inputValue, setInputValue] = useState('');

  // State to hold debounced input value
  const debouncedInputValue = useDebounce(inputValue, 500);

  // Handler function for input change
  const handleChange = (e) => {
    setInputValue(e.target.value);
  };

  return (
    <div>
      <h1>Debounce Example</h1>
      <input
        type="text"
        value={inputValue}
        onChange={handleChange}
        placeholder="Type something..."
      />
      <p>Debounced value: {debouncedInputValue}</p>
    </div>
  );
};

export default MyComponent;

In this example:

  • We make a functional component named MyComponent.

  • We use the useState hook to track the input value (inputValue).

  • We use the useDebounce hook to delay updating the input value (debouncedInputValue).

  • When the input value (inputValue) changes, the useDebounce hook waits for 500 milliseconds to update the debounced value (debouncedInputValue), but only if there are no new changes.

  • We display the debounced value (debouncedInputValue) in the component, showing the latest input value after the specified delay.

Did you find this article valuable?

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