Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 3, 2024 07:54
Show Gist options
  • Save freddi301/0f3c47aab40a3d5d8927ac7b61db7a35 to your computer and use it in GitHub Desktop.
Save freddi301/0f3c47aab40a3d5d8927ac7b61db7a35 to your computer and use it in GitHub Desktop.
React hook use adjusted refreshing value
// adjust refreshing value in time for more pleasant loading indicator animation
// it is true if it was awlays true in the last 0.3 seconds
// it stays true for at least 1.0 second
function useAdjustedRefreshingValue(isRefreshing: boolean): boolean {
const DO_NOT_SHOW_BEFORE_MILLIS = 300;
const SHOW_FOR_AT_LEAST_MILLIS = 1000;
const [adjustedIsRefreshing, setAdjustedIsRefreshing] =
React.useState(isRefreshing);
const [isRefrescingSince, setIsRefreshingSince] = React.useState(0);
React.useEffect(() => {
if (isRefreshing) {
setIsRefreshingSince(Date.now());
const timeout = setTimeout(() => {
setAdjustedIsRefreshing(true);
}, DO_NOT_SHOW_BEFORE_MILLIS);
return () => clearTimeout(timeout);
}
return () => undefined;
}, [isRefreshing]);
React.useEffect(() => {
if (!isRefreshing) {
const timeout = setTimeout(
() => setAdjustedIsRefreshing(false),
Math.max(
0,
DO_NOT_SHOW_BEFORE_MILLIS +
SHOW_FOR_AT_LEAST_MILLIS -
(Date.now() - isRefrescingSince)
)
);
return () => clearTimeout(timeout);
}
return () => undefined;
}, [isRefrescingSince, isRefreshing]);
return adjustedIsRefreshing;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment