DEV Community

Discussion on: Throttling and Debouncing in ReactJS

Collapse
 
aminnairi profile image
Amin • Edited

Hi Manish and thanks for this interesting article,

You could also use a custom hook to create your own version of React.useCallback, but with throttling/debouncing.

import React from "react";

expprt const useThrottledCallback = (delay, dependencies, callback) => {
  const [timeoutIdentifier, setTimeoutIdentifier] = React.useState(null);

  return React.useCallback((...parameters) => {
    if (timeoutIdentifier !== null) {
      window.clearTimeout(timeoutIdentifier);
    }

    setTimeoutIdentifier(window.setTimeout(() => {
      setTimeoutIdentifier(null);
      callback(...parameters);
    }, delay));
  }, dependencies);
};
Enter fullscreen mode Exit fullscreen mode

Here is one example use-case scenario.

import {useThrottledCallback} from "./hooks/throttling";
import React from "react";

export const App = () => {
  const [search, setSearch] = React.useState("");
  const [result, setResult] = React.useState([]);

  const fetchResult = useThrottledCallback(1500, [search, setResult], () => {
    window.fetch(`https://jsonplaceholder.typicode.com/${search}`).then(response => {
      return response.json();
    }).then(newResult => {
      setResult(newResult);
    }).catch(() => {
      setResult([]);
    });
  });

  const onSearch = React.useCallback(event => {
    setSearch(event.target.value);
  }, [setSearch]);

  React.useEffect(() => {
    fetchResult();
  }, [search]);

  return (
    <div>
      <div>
        <label htmlFor="search">JSONPlaceholders endpoint</label>
        <input id="search" type="text" onInput={onSearch} value={search} />
      </div>
      <pre><code>{JSON.stringify(result, null, 2)}</code></pre>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Seems like there is a NPM package that does that too, but I haven't got the occasion to test it out.

Collapse
 
trex777 profile image
Manish Kumar Sahu • Edited

Thanks, this is so much helpful, specially for reusability of the code, will definitely try this out.