(
options: { immediate?: boolean; timeoutMs?: number } = {},
)
| 10 | * (useful when the deferred content is already in view). |
| 11 | */ |
| 12 | export function useDeferredLoad( |
| 13 | options: { immediate?: boolean; timeoutMs?: number } = {}, |
| 14 | ): boolean { |
| 15 | const { immediate = false, timeoutMs = DEFAULT_TIMEOUT_MS } = options; |
| 16 | const [isReady, setIsReady] = React.useState(immediate); |
| 17 | |
| 18 | React.useEffect(() => { |
| 19 | if (isReady) { |
| 20 | return; |
| 21 | } |
| 22 | |
| 23 | if (immediate) { |
| 24 | setIsReady(true); |
| 25 | return; |
| 26 | } |
| 27 | |
| 28 | const activate = () => { |
| 29 | setIsReady(true); |
| 30 | }; |
| 31 | |
| 32 | if ("requestIdleCallback" in window) { |
| 33 | const idleId = window.requestIdleCallback(activate, { |
| 34 | timeout: timeoutMs, |
| 35 | }); |
| 36 | return () => { |
| 37 | window.cancelIdleCallback(idleId); |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | const timeoutId = globalThis.setTimeout(activate, timeoutMs); |
| 42 | return () => { |
| 43 | globalThis.clearTimeout(timeoutId); |
| 44 | }; |
| 45 | }, [immediate, isReady, timeoutMs]); |
| 46 | |
| 47 | return isReady; |
| 48 | } |
| 49 | |
| 50 | let hasCompletedStartup = false; |
| 51 |
no outgoing calls
no test coverage detected