debounce react code example

Example 1: onchange debounce react

import React, { useCallback } from 'react';
import _ from 'lodash';

const MyComponent = ({ data, handleInputChange }) => {
  const debounceFunc = useCallback(
    _.debounce(e => handleInputChange(e), 500),
    []
  );

  const handleChange = e => {
    debounceFunc(e);
  };
  return <TextInput data={data} onChange={handleChange} />;
};

export default MyComponent;

Example 2: how to add debounce in react redux js

function SearchInput() {
  const [realTimeValue, setRealTimeValue] = useState('');

  const debouncedValue = useDebouncedValue(realTimeValue, 500); // this value will pick real time value, but will change it's result only when it's seattled for 500ms

  useEffect(() => {
    // this effect will be called on seattled values
    api.fetchSearchResults(debouncedValue);
  }, [debouncedValue])

  return <input onChange={event => setRealTimeValue(event.target.value)} />
}