Created
October 4, 2019 14:05
-
-
Save dandelionadia/f299dcf4cc1036a873b97819c6e411b3 to your computer and use it in GitHub Desktop.
react functional component debounce
This file contains 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
import React, { useState, useRef } from 'react' | |
import debounce from 'lodash.debounce' | |
const Search = () => { | |
// state text which was written in the input | |
const [value, setValue] = useState('') | |
// using "useRef" so that React doesn't create | |
// debounced function on each render (after state update). | |
const doSearch = useRef( | |
// using debounce to delay request to backend | |
debounce(searchQuery => { | |
// backend request to do search | |
fetch(`https://back.end?q=${searchQuery}`) | |
}, 300) | |
).current | |
const handleChange = event => { | |
const nextValue = event.target.value | |
// update input value | |
setValue(nextValue) | |
// do search request | |
doSearch(nextValue) | |
} | |
return ( | |
<input value={value} onChange={handleChange} /> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment