Skip to content

Instantly share code, notes, and snippets.

@gabrielmlinassi
Created July 19, 2022 02:48
Show Gist options
  • Save gabrielmlinassi/c7ee3f2b10c405a83e8f04a260f3af1e to your computer and use it in GitHub Desktop.
Save gabrielmlinassi/c7ee3f2b10c405a83e8f04a260f3af1e to your computer and use it in GitHub Desktop.
How to implement debounce
// #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..." />
);
}
@gabrielmlinassi
Copy link
Author

gabrielmlinassi commented Jul 19, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment