Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created May 5, 2023 08:30
Show Gist options
  • Save freddi301/c14b7fb770354cd81af39f1acfc6a435 to your computer and use it in GitHub Desktop.
Save freddi301/c14b7fb770354cd81af39f1acfc6a435 to your computer and use it in GitHub Desktop.
useValueWithTimeToLive
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