From the author of the Telegram channel REACT NATIVE HUB
Join a growing community of React Native Devs! 👆
When handling search inputs or live updates, debouncing prevents excessive API requests by delaying execution until the user stops typing.
Implementation:
import { useState, useEffect } from "react";
function useDebounce(value, delay = 500) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(handler);
}, [value, delay]);
return debouncedValue;
}
export default useDebounce;
Usage Example:
const [searchTerm, setSearchTerm] = useState("");
const debouncedSearch = useDebounce(searchTerm, 300);
useEffect(() => {
if (debouncedSearch) {
fetch(`https://api.example.com/search?q=${debouncedSearch}`)
.then((res) => res.json())
.then((data) => console.log(data));
}
}, [debouncedSearch]);
<TextInput
placeholder="Search..."
onChangeText={(text) => setSearchTerm(text)}
/>;
✅ Why Use It?
- Reduces unnecessary API calls
- Improves performance in search fields
- Ensures a smooth user experience
About me: My name is Arsen, and I am a react native developer and owner of the TG channel 👇
🔗 Join TG community for React Native Devs: REACT NATIVE HUB
Top comments (0)