useDebounce React Hook

useDebounce React Hook

Code

import { useState, useEffect } from 'react';
import { useEffect, useRef } from "react";

export const useDebounce = (value, delay = 1000, callback) => {
  const timer = useRef(null);

  useEffect(() => {
    clearTimeout(timer.current);

    if (value && callback) {
      timer.current = setTimeout(callback, delay);
    }

    return () => {
      clearTimeout(timer.current);
    };
  }, value);
};

Example

import React, { useState } from 'react';
import { useDebounce } from './useDebounce';

const Search = () => {
  const [searchTerm, setSearchTerm] = useState('');

  const callbackFunction = () => {
    console.log('searching for ', searchTerm);
    // network request to search for searchTerm
  };

  useDebounce(searchTerm, 500, callbackFunction);

  // ... other code

  return (
    <div>
      <input
        type="text"
        placeholder="Search..."
        onChange={e => setSearchTerm(e.target.value)}
      />
    </div>
  );
};

[Top]

Share: