DEV Community

Discussion on: React Hooks | My Package

Collapse
 
daxsoft profile image
Michael Willian Santos

Sure thing, dude:
Example using the 'search box logic'. For each word that the users set on search box, it will delay by 750 ms to update the logic (in this case, a new request to the database)

const [search, setSearch] = useState<string>("")
const debounceSearchValue = useDebounce(() => search, 750);
const isSearchValid = useMemo<boolean>(
        () =>  search.length > 0,
        [search]
);
useEffect(() => {
        if (isSearchValid) {
            // stuffs..
        }
}, [debounceSearchValue]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gusyavo profile image
Gustavo

Thanks a lot for your answer. I am new to react hooks, so there is one thing I don't quite understand. Can you debounce a function instead of a value? I need to debounce a function (that makes a request to an API and sets a state with the answer) each time a state (a kind of complex object) changes. I am not sure if that is what the example shows.

Thread Thread
 
daxsoft profile image
Michael Willian Santos

You are welcome :)
Sure thing you can debounce a function, on the example that I have give you, I have put a value because the state itself isn't a function. But you can use a function, however, this function need to return a value that will be changed (to get debounced)