-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
useLoadOnMount.mjs
73 lines (63 loc) · 2.25 KB
/
useLoadOnMount.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// @ts-check
/**
* @import Cache, { CacheKey } from "./Cache.mjs"
* @import { Loader } from "./types.mjs"
*/
import React from "react";
import HYDRATION_TIME_MS from "./HYDRATION_TIME_MS.mjs";
import HydrationTimeStampContext from "./HydrationTimeStampContext.mjs";
import useCache from "./useCache.mjs";
/**
* React hook to automatically load a {@link Cache.store cache store} entry
* after the component mounts or the {@link CacheContext cache context} or any
* of the arguments change, except during the
* {@link HYDRATION_TIME_MS hydration time} if the
* {@link HydrationTimeStampContext hydration time stamp context} is populated
* and the {@link Cache.store cache store} entry is already populated.
* @param {CacheKey} cacheKey Cache key.
* @param {Loader} load Memoized function that starts the loading.
*/
export default function useLoadOnMount(cacheKey, load) {
if (typeof cacheKey !== "string")
throw new TypeError("Argument 1 `cacheKey` must be a string.");
if (typeof load !== "function")
throw new TypeError("Argument 2 `load` must be a function.");
const cache = useCache();
const hydrationTimeStamp = React.useContext(HydrationTimeStampContext);
if (
// Allowed to be undefined for apps that don’t provide this context.
hydrationTimeStamp !== undefined &&
typeof hydrationTimeStamp !== "number"
)
throw new TypeError("Hydration time stamp context value must be a number.");
const startedRef = React.useRef(
/**
* @type {{
* cache: Cache,
* cacheKey: CacheKey,
* load: Loader,
* } | undefined}
*/ (undefined),
);
React.useEffect(() => {
if (
// Loading the same as currently specified wasn’t already started.
!(
startedRef.current &&
startedRef.current.cache === cache &&
startedRef.current.cacheKey === cacheKey &&
startedRef.current.load === load
) &&
// Waterfall loaded cache isn’t being hydrated.
!(
cacheKey in cache.store &&
hydrationTimeStamp &&
// Within the hydration time.
performance.now() - hydrationTimeStamp < HYDRATION_TIME_MS
)
) {
startedRef.current = { cache, cacheKey, load };
load();
}
}, [cache, cacheKey, hydrationTimeStamp, load]);
}