Skip to content

Instantly share code, notes, and snippets.

@jhavenz
Created April 3, 2023 04:01
Show Gist options
  • Save jhavenz/9d2ff9ec8c7492bf4bd927e77da4917d to your computer and use it in GitHub Desktop.
Save jhavenz/9d2ff9ec8c7492bf4bd927e77da4917d to your computer and use it in GitHub Desktop.
useTimeout React Hook
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 }
}
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