🔁 Retry & Debounce in React
When working with APIs or user input, it's important to add robustness. Retry logic handles temporary failures, while Debounce reduces unnecessary requests (e.g., during typing).
🔄 1. Retry API Calls
If an API fails (e.g., due to network issues), retry a few times before showing an error:
async function fetchWithRetry(url, retries = 3, delay = 1000) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error("Fetch failed");
return await res.json();
} catch (err) {
if (retries > 0) {
await new Promise(resolve => setTimeout(resolve, delay));
return fetchWithRetry(url, retries - 1, delay);
} else {
throw err;
}
}
}
⏱️ 2. Debounce Input (Manual)
Debouncing limits how often a function is called during rapid events (like typing):
function useDebounce(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debounced;
}
// Usage:
const search = useDebounce(inputValue, 500);
📦 3. Debounce with Lodash
import { debounce } from "lodash";
const handleChange = debounce((value) => {
console.log("Debounced:", value);
}, 300);
// <input onChange={(e) => handleChange(e.target.value)} />
✅ 4. Best Practices
- Use retry for non-critical API calls with flaky networks
- Use debounce in live search, input forms, or resize events
- Throttle (not debounce) when you need regular updates