Custom debounce function as a hook
Skip function calls until a specified delay has elapsed
Implementation
useDebounce.ts
import { useEffect, useState } from "react";
export const useDebounce = <T>(value: T, delay = 500) => {
const [debouncedValue, setDebouncedValue] = useState < T > value;
useEffect(() => {
const timeout = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(timeout);
}, [value, delay]);
return debouncedValue;
};
Usage
Demo.tsx
export default function Demo() {
const [users, setUsers] = useState<User[]>([]);
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search);
useEffect(() => {
const loadUsers = async () => {
setLoading(true);
const users = await fetchUsers(debouncedSearch);
setUsers(users);
setLoading(false);
};
loadUsers();
}, [debouncedSearch]);
return (
<div className='tutorial'>
<SearchBar onChange={setSearch} />
{users.map((user) => {
return <div key={user.id}>{user.name}</div>;
})}
</div>
);