Created
May 5, 2023 08:30
-
-
Save freddi301/c14b7fb770354cd81af39f1acfc6a435 to your computer and use it in GitHub Desktop.
useValueWithTimeToLive
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
function useValueWithTimeToLive<T>() { | |
const [state, setState] = React.useState<{ value: T | undefined; timeToLive: number | undefined }>({ | |
value: undefined, | |
timeToLive: undefined, | |
}); | |
const setValueWithTimeToLive = React.useCallback((value: T, timeToLive: number) => { | |
setState({ value, timeToLive }); | |
}, []); | |
React.useEffect(() => { | |
if (state.timeToLive !== undefined) { | |
const timeout = setTimeout(() => { | |
setState({ value: undefined, timeToLive: undefined }); | |
}, state.timeToLive); | |
return () => { | |
clearTimeout(timeout); | |
}; | |
} | |
}, [state.timeToLive]); | |
return [state.value, setValueWithTimeToLive]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment