Let's assume that you are querying an API endpoint:
jsximport React, { useEffect, useState } from 'react' const Search = () => { const [query, setQuery] = useState('') useEffect(() => { const getData = async () => { let res = await fetch(`https://api.cool.com/q=${query}`) let val = await res.json() } getData() }, [query]) return <input value = {query} onChange = {e => setQuery(e.target.value)}/> } export default Search
The problem with the previous approach is that every time that the user types a new key, a new request is perform. As the APIs have limitations in the number of requests per second, you'll reach the limitation quickly and you'll be blocked from using that API.
Hence, it's better to wait until the user stops typing to reduce the number of requests per second.
Let's assume that a user stops typing after 1.5 seconds of inactivity (you can fine tune this value depending on your preferences). You can modify the useEffect()
hook accordingly:
jsxuseEffect(() => { const getData = async () => { let res = await fetch(`https://api.cool.com/q=${query}`) let val = await res.json() } // Function launches after 1.5 seconds (1500 ms) of the last keystroke // On first render you don't want to launch anything // Thus, you check if the user typed a query at first let timer = setTimeout(() => { if(query) getData() }, 1500) // If useEffect() relaunches, you clear the function // That means, the previous function won't launch // Thus, won't send a request to the API return () => clearTimeout(timer) }, [query])
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.