All files / src/hooks useDelayedFlag.ts

100% Statements 12/12
100% Branches 8/8
100% Functions 4/4
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21                  5x 626x   626x 626x 128x 11x 11x   626x    
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
 
import { useEffect, useState } from "react";
 
/**
 * `value`, but only turning true once it has stayed true for `delayMs`.
 * Used for loading indicators so quick loads don't flash them on screen.
 */
export const useDelayedFlag = (value: boolean, delayMs: number): boolean => {
	const [delayed, setDelayed] = useState(false);
	// Turning off starts the wait over for the next time it turns on.
	if (!value && delayed) setDelayed(false);
	useEffect(() => {
		if (!value) return;
		const t = setTimeout(() => setDelayed(true), delayMs);
		return () => clearTimeout(t);
	}, [value, delayMs]);
	return value && delayed;
};