Skip to content

feat: add image pre-loading hooks #10015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: update logic issue with cleanup functions
  • Loading branch information
Parkreiner committed Oct 4, 2023
commit 9ed0dc3cd625f6fb7522b15194ddc50be0593ac0
22 changes: 14 additions & 8 deletions site/src/hooks/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,15 @@ function preloadImages(imageUrls?: readonly string[]): () => void {
* from making requests.
*/
export function useThrottledImageLoader(throttleTimeMs = 500) {
/**
* It's possible to reduce the amount of state by only having the cleanup ref;
* tried it, but it made the code a lot harder to read and reason about
*/
const throttledRef = useRef(false);
const loadedCleanupRef = useRef<(() => void) | null>(null);
const componentCleanupRef = useRef<(() => void) | null>(null);

useEffect(() => {
loadedCleanupRef.current?.();
componentCleanupRef.current?.();
}, [throttleTimeMs]);

return useCallback(
Expand All @@ -114,20 +118,22 @@ export function useThrottledImageLoader(throttleTimeMs = 500) {
}

throttledRef.current = true;
const cleanup = preloadImages(imgUrls);
loadedCleanupRef.current = cleanup;
const imagesCleanup = preloadImages(imgUrls);

const timeoutId = window.setTimeout(() => {
throttledRef.current = false;
}, throttleTimeMs);

return () => {
cleanup();
loadedCleanupRef.current = null;

const componentCleanup = () => {
imagesCleanup();
window.clearTimeout(timeoutId);

throttledRef.current = false;
componentCleanupRef.current = null;
};

componentCleanupRef.current = componentCleanup;
return componentCleanup;
},
[throttleTimeMs],
);
Expand Down