Skip to content

Instantly share code, notes, and snippets.

@4sskick
Last active May 23, 2025 03:49
Show Gist options
  • Save 4sskick/c30bae0c5cc86ba747c88932d4c354eb to your computer and use it in GitHub Desktop.
Save 4sskick/c30bae0c5cc86ba747c88932d4c354eb to your computer and use it in GitHub Desktop.
export const useDebounce = (callback: Function, delay: number = 250)=>{
//create ref to hold the references created
const timer = useRef<Nodejs.Timeout>()
return useCallback(()=>{
const executeLater = ()=>{
//check if timer still holding the references as indicate that timer still active
//clear that
if(timer.current)clearTimeout(timer.current);
callback()
}
//set the new one after clear timer reference
timer.current = setTimeout(executeLater, delay);
},[callback, delay])
}
// in use
export default function performSearch(){
const [searchTerm, setSeaarchTerm] = useState<string>('');
const [result, setResult] = useState<string>('');
const performSearch = ()=>{
setResult(`you search for ${searchTerm}`)
}
const debounceSearch = useDebounce(performSearch, 500);
const handleinputChange = (text:string)=>{
setSeaarchTerm(text)
debounceSearch()
}
return(
<View>
<TextInput
placeholder="type here..."
value={searchTerm}
onChangetext={handleinputChange}
/>
<Text>{result}</Text>
</View>
)
}
Debounce based on https://medium.com/swlh/using-a-debounced-callback-in-react-ade57d31ca6b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment