Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Created January 16, 2023 17:29
Show Gist options
  • Save ValentaTomas/032b18c9a39512bad7fcc397bb59fc08 to your computer and use it in GitHub Desktop.
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
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