Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created June 22, 2020 12:00
Show Gist options
  • Save smitroshin/0949f73f96ab82f8327b334b9f83a04f to your computer and use it in GitHub Desktop.
Save smitroshin/0949f73f96ab82f8327b334b9f83a04f to your computer and use it in GitHub Desktop.
Using throttle and debounce in a React function component
/**
* 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