A simple and reusable debounce hook for React
npm install use-debounce-hook-webmarkdown
npm i use-debounce-hook-web
`
Basic Usage
`js
useDebounce(value, delay)
`
`js
import { useDebounce } from 'use-debounce-hook-web';
import { useState } from 'react';
const SearchInput = () => {
const [value, setValue] = useState('');
const debouncedValue = useDebounce(value, 500);
return (
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Search..."
/>
);
};
export default SearchInput;
`
Advanced Usage
`js
useDebounce(value, delay, options)
`
`js
const debouncedValue = useDebounce(value, 500, {
immediate: true,
maxWait: 2000
});
`
`js
const debouncedValue = useDebounce(value, 500, {
maxWait: 2000
});
`
`js
import { useEffect, useState } from "react";
import { useDebounce } from "react-use-debounce";
function SearchUsers() {
const [query, setQuery] = useState("");
const debouncedQuery = useDebounce(query, 500, {
immediate: true,
maxWait: 2000
});
useEffect(() => {
if (!debouncedQuery) return;
fetch(https://api.example.com/users?q=${debouncedQuery})
.then(res => res.json())
.then(data => console.log(data));
}, [debouncedQuery]);
return (
placeholder="Search users..."
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
);
}
export default SearchUsers;
``