Created
July 17, 2022 16:21
-
-
Save codemile/768d792c9eb48b61125e7c6a6c77b613 to your computer and use it in GitHub Desktop.
React hook for bouncing a value back to it's default after a delay.
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 {useEffect, useState} from 'react'; | |
export const useBounceValue = <TValue,>( | |
newValue: TValue, | |
defaultValue: TValue, | |
delay: number | |
) => { | |
const [value, setValue] = useState<TValue>(defaultValue); | |
useEffect(() => { | |
setValue(newValue); | |
const id = setTimeout(() => setValue(defaultValue), delay); | |
return () => clearTimeout(id); | |
}, [newValue, defaultValue, delay]); | |
return value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment