Created
April 3, 2023 03:55
-
-
Save jhavenz/4dde315cf54dba33218f1fd169d9faa9 to your computer and use it in GitHub Desktop.
useDebounce React Hook
This file contains hidden or 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
# |
This file contains hidden or 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 useTimeout from '@/hooks/useTimeout/useTimeout' | |
import React, { useEffect } from 'react' | |
export default function useDebounce(callback, delay, dependencies) { | |
const { reset, clear } = useTimeout(callback, delay) | |
useEffect(reset, [...dependencies, reset]) | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
useEffect(clear, []) | |
} |
This file contains hidden or 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 useDebounce from '@/hooks/useDebounce/useDebounce' | |
import React, { useState } from 'react' | |
export default function UseDebounceExampleComponent() { | |
const [count, setCount] = useState(10) | |
useDebounce(() => alert(count), 1000, [count]) | |
return ( | |
<div> | |
<div>{count}</div> | |
<button onClick={() => setCount((c) => c + 1)}>Increment</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment