useDebounce — delay value updates until user stops changing.
Implementation:
1import { useState, useEffect } from "react";23function useDebounce<T>(value: T, delay: number): T {4 const [debouncedValue, setDebouncedValue] = useState(value);56 useEffect(() => {7 const handler = setTimeout(() => {8 setDebouncedValue(value);9 }, delay);1011 return () => clearTimeout(handler);12 }, [value, delay]);1314 return debouncedValue;15}1617// Usage18function SearchInput() {19 const [query, setQuery] = useState("");20 const debouncedQuery = useDebounce(query, 500);2122 useEffect(() => {23 if (debouncedQuery) {24 performSearch(debouncedQuery);25 }26 }, [debouncedQuery]);2728 return <TextInput value={query} onChangeText={setQuery} />;29}
Debounced callback hook:
1function useDebouncedCallback(callback: Function, delay: number) {2 const timeoutRef = useRef<NodeJS.Timeout>();34 return useCallback((...args) => {5 clearTimeout(timeoutRef.current);6 timeoutRef.current = setTimeout(() => {7 callback(...args);8 }, delay);9 }, [callback, delay]);10}