Skip to content

Instantly share code, notes, and snippets.

@codemile
Created July 17, 2022 16:21
Show Gist options
  • Save codemile/768d792c9eb48b61125e7c6a6c77b613 to your computer and use it in GitHub Desktop.
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.
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