Skip to content

Instantly share code, notes, and snippets.

@adamhenson
Last active September 9, 2019 23:42
Show Gist options
  • Save adamhenson/b38b2563797593d59b38163df9398277 to your computer and use it in GitHub Desktop.
Save adamhenson/b38b2563797593d59b38163df9398277 to your computer and use it in GitHub Desktop.
Example Debounce Function with useRef and useEffect
import React, { useEffect, useRef, useState } from 'react';
import { debounce } from 'throttle-debounce';
const DEBOUNCE_MS = 200;
export default () => {
const [value, setValue] = useState('');
const [finalValue, setFinalValue] = useState('');
// we use `useRef` so that we don't redefine the function on every update
// and in turn erase the debounce functionality.
const setValueDebounced = useRef(
debounce(DEBOUNCE_MS, setFinalValue)
);
// set the search term using `debounce` which introduces an intentional delay
// - hence the side-effect.
useEffect(() => {
setValueDebounced.current(value);
}, [value]);
// just an example
return (
<input
onChange={(event) => setValue(event.currentTarget.value)}
value={finalValue}
/>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment