Created
July 19, 2022 02:48
-
-
Save gabrielmlinassi/c7ee3f2b10c405a83e8f04a260f3af1e to your computer and use it in GitHub Desktop.
How to implement 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
// #1. With a controlled input | |
import { useState, useEffect } from 'react'; | |
const debounce = require("lodash.debounce"); | |
function SearchBar({ onSearch, wait = 500 }) { | |
const [value, setValue] = useState(''); | |
const [searchTerm, setSearchTerm] = useState(''); | |
useEffect(() => { | |
onSearch && onSearch(searchTerm); | |
}, [searchTerm]); | |
const debouncedSearch = useCallback( | |
debounce((term) => setSearchTerm(term), wait), | |
[] | |
); | |
function onChange(e) { | |
setValue(e.target.value); | |
debouncedSearch(e.target.value); | |
} | |
return ( | |
<input | |
value={value} | |
onChange={onChange} | |
type="text" | |
placeholder="Search names..." | |
/> | |
); | |
} | |
// #2. With an un-controlled input | |
function SearchBar({ onSearch, wait = 1000 }) { | |
const [searchTerm, setSearchTerm] = useState(''); | |
useEffect(() => { | |
onSearch && onSearch(searchTerm); | |
}, [searchTerm]); | |
const onChange = debounce((e) => setSearchTerm(e.target.value), wait); | |
return ( | |
<input onChange={onChange} type="text" placeholder="Search names..." /> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PS. Search input usually doesn't need to be controlled because we're not interested in the current value but rather in the debounced one. So I'd give preference for method #2