Skip to content

Instantly share code, notes, and snippets.

@ciel334288
Last active December 31, 2020 09:26
Show Gist options
  • Select an option

  • Save ciel334288/598700668b4da1eceecbff80959e4387 to your computer and use it in GitHub Desktop.

Select an option

Save ciel334288/598700668b4da1eceecbff80959e4387 to your computer and use it in GitHub Desktop.
Debouncing event example in a Reactjs component
import React, { useState, useEffect, useCallback } from 'react';
import { debounce } from "lodash";
export default function Cz() {
const delay = 3000;
const [queryParams, setQueryParams] = useState({ search_field: '' });
const delayedQuery = useCallback(debounce(() => {
alert(1); // debounced func
}, delay), [queryParams]);
useEffect(() => {
delayedQuery();
// Cancel the debounce on useEffect cleanup
return delayedQuery.cancel;
}, [queryParams, delayedQuery]);
const handleChange = (e) => setQueryParams({ queryParams..., [e.target.name]: e.target.value });
return ( <input name="search_field" onChange={ handleChange } value={ queryParams.search_field } placeholder="search..." /> )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment