Last active
May 23, 2025 03:49
-
-
Save 4sskick/c30bae0c5cc86ba747c88932d4c354eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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