Skip to content

Instantly share code, notes, and snippets.

@crrmacarse
Last active May 19, 2020 15:31
Show Gist options
  • Save crrmacarse/a1efe83ec68ae093ed0e285cff693528 to your computer and use it in GitHub Desktop.
Save crrmacarse/a1efe83ec68ae093ed0e285cff693528 to your computer and use it in GitHub Desktop.
Limit trigger of useEffect ala componentDidUpdate behaviour
const isInitialMount = useRef(true);
const [search, setSearch] = useState<string>();
// https://stackoverflow.com/questions/55075604/react-hooks-useeffect-only-on-update
useEffect(() => {
let debounceFunc: NodeJS.Timeout;
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
debounceFunc = setTimeout(() => {
handleSearch(search);
}, 1000);
}
return () => clearTimeout(debounceFunc);
}, [search]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment