Created
April 3, 2023 04:01
-
-
Save jhavenz/9d2ff9ec8c7492bf4bd927e77da4917d to your computer and use it in GitHub Desktop.
useTimeout 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 { useCallback, useEffect, useRef } from 'react' | |
export default function useTimeout(callback, delay) { | |
const callbackRef = useRef(callback) | |
const timeoutRef = useRef() | |
useEffect(() => { | |
callbackRef.current = callback | |
}, [callback]) | |
const set = useCallback(() => { | |
timeoutRef.current = setTimeout(() => callbackRef.current(), delay) | |
}, [delay]) | |
const clear = useCallback(() => { | |
timeoutRef.current && clearTimeout(timeoutRef.current) | |
}, []) | |
useEffect(() => { | |
set() | |
}, [delay, set, clear]) | |
const reset = useCallback(() => { | |
clear() | |
}, [clear, set]) | |
return { reset, 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 useTimeout from '@/hooks/useTimeout/useTimeout' | |
import React, { useState } from 'react' | |
export default function UseTimeoutExampleComponent() { | |
const [count, setCount] = useState(10) | |
const [clear, reset] = useTimeout(() => setCount(0), 1000) | |
return ( | |
<div> | |
<div>{count}</div> | |
<button onClick={() => setCount((c) => c + 1)}>Increment</button> | |
<button onClick={clear}>Clear Timeout</button> | |
<button onClick={reset}>Reset Timeout</button> | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment