React Async Data fetch

State Update is Asynchronous (slower than what you expect!)

const handleChange = (event) => {  setInput(event.target.value);
fetchData(input); // x , prev input value
fetchData(event.target.value); // o , current value
};
useEffect(()=>{
console.log(input) // o , current input value
},[input])const handleChange = (event) => { setInput(event.target.value);
fetchData(input); // x , prev input value
fetchData(event.target.value); // o , current input value
};
useEffect(()=>{
async function fetchData(input) {...}
const data = await fetchData()
setData(data)
},[input])const handleChange = (event) => {
setInput(event.target.value)
}

Debounce and Re-render

Debounce image from CSS-Tricks https://css-tricks.com/debouncing-throttling-explained-examples/
Debounce Image from CSS-Tricks https://css-tricks.com/debouncing-throttling-explained-examples/
Red arrow shows executing debounce across re-rendering without useCallback
function MySearch() {  const [input, setInput] = useState('')  // create memoized version of debounced data fetch function  const debouncedFetchData = useCallback(debounce(fetchData, 500),   []);  // call memoized debounced function in the event handler so the 
intermediate searches are cancelled by debounce while the user types
const handleChange = (event) => {
setInput(event.target.value);
debouncedFetchData(event.target.value);
};
return <input onChange={handleChange} value={input} />}

References

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store