Created
June 22, 2020 12:00
-
-
Save smitroshin/0949f73f96ab82f8327b334b9f83a04f to your computer and use it in GitHub Desktop.
Using throttle and debounce in a React function component
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
/** | |
* Source: https://medium.com/@rajeshnaroth/using-throttle-and-debounce-in-a-react-function-component-5489fc3461b3 | |
*/ | |
const Search = () => { | |
const [userQuery, setUserQuery] = useState(""); | |
const delayedQuery = useCallback(_.debounce(q => sendQuery(q), 500), []); | |
// alternative | |
// const delayedQuery = useRef(_.debounce(q => sendQuery(q), 500)).current; | |
const onChange = e => { | |
setUserQuery(e.target.value); | |
delayedQuery(e.target.value); | |
}; | |
return ( | |
<div> | |
<label>Search Fixed:</label> | |
<input onChange={onChange} value={userQuery} /> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment