-
-
Save ciel334288/598700668b4da1eceecbff80959e4387 to your computer and use it in GitHub Desktop.
Debouncing event example in a Reactjs component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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