Skip to content

Instantly share code, notes, and snippets.

@WebD00D
Created October 9, 2019 00:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebD00D/4ac7c32676bb06ebe448c83dbc86af13 to your computer and use it in GitHub Desktop.
Save WebD00D/4ac7c32676bb06ebe448c83dbc86af13 to your computer and use it in GitHub Desktop.
Debounce React Hook
import React, { useState, useEffect } from 'react';
const debounce = (value, delay) => {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(
() => {
// Set debouncedValue to value (passed in) after the specified delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Return a cleanup function that will be called every time ...
// ... useEffect is re-called. useEffect will only be re-called ...
// ... if value changes (see the inputs array below).
// This is how we prevent debouncedValue from changing if value is ...
// ... changed within the delay period. Timeout gets cleared and restarted.
// To put it in context, if the user is typing within our app's ...
// ... search box, we don't want the debouncedValue to update until ...
// ... they've stopped typing for more than 500ms.
return () => {
clearTimeout(handler);
};
},
// Only re-call effect if value changes
// You could also add the "delay" var to inputs array if you ...
// ... need to be able to change that dynamically.
[value]
);
return debouncedValue;
}
export default debounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment