Skip to main content

Deduplicate API calls (Debounce)

  • especially useful when reliant on third party libraries like Auth0 and you have a dependency on user login.

Code​

  • debounce.js
import { useEffect, useState } from "react";

export function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);

useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);

return () => {
clearTimeout(timer);
};
}, [value, delay]);

return debouncedValue;
}

Usage​

const [localUser, setLocalUser] = useState(null);
const debouncedUser = useDebounce(localUser, 300);

useEffect(() => {
if (debouncedSearchTerm) {
// Perform action with debounced value
console.log('Searching for:', debouncedSearchTerm);
// You would typically make an API call or perform some other action here
}
}, [debouncedSearchTerm]);