Created
January 16, 2023 17:29
-
-
Save ValentaTomas/032b18c9a39512bad7fcc397bb59fc08 to your computer and use it in GitHub Desktop.
Set state that will expire and revert to the default state after a timeout
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 debounce from 'lodash.debounce' | |
import { useCallback, useMemo, useState } from 'react' | |
export interface Props<T> { | |
defaultValue: T | |
timeout: number // in ms | |
} | |
function useExpiringState<T>({ | |
defaultValue, | |
timeout, | |
}: Props<T>): [T, (value: T) => void] { | |
const [value, setValue] = useState(defaultValue) | |
const enqueExpiration = useMemo(() => debounce(() => { | |
setValue(defaultValue) | |
}, timeout, { | |
leading: false, | |
trailing: true, | |
}), [timeout, defaultValue]) | |
const set = useCallback((newValue: T) => { | |
setValue(newValue) | |
enqueExpiration() | |
}, [enqueExpiration]) | |
return [value, set] | |
} | |
export default useExpiringState |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment