Last active
September 9, 2019 23:42
-
-
Save adamhenson/b38b2563797593d59b38163df9398277 to your computer and use it in GitHub Desktop.
Example Debounce Function with useRef and useEffect
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
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