// Then, create promises for each font family in the tuples
const promises = fontTuples.flatMap(([headerFont, bodyFont]) => [
retryPromise(() => nir(headerFont)).catch(() => setHasError(true)),
retryPromise(() => nir(bodyFont)).catch(() => setHasError(true)),
]);
IGNORE_WHEN_COPYING_START
Use code with caution.
IGNORE_WHEN_COPYING_END
}, [fontData, nir]);
return { isLoading, hasError };
}
export default useLoadFonts;
ignoring the timing / debug code
is there a nicer way to handle the fact that fonts can change, we need an accurate loading / error state, and we don't want duplicate requests, if possible, while keeping the code minimal, clean
// Requirments:
// - Loading state stays true until all fonts are really loaded (not empty, empty = loading)
// - When fonts change, new fonts are loaded & is loading is updated
// - Fonts that are already fetched are not fetched again
Assistant
To meet the requirements of accurate loading state, no duplicate requests, responsive to font data changes, and minimal, clean code, we can refactor the useLoadFonts custom hook as follows:
✅ Key Improvements
Accurate Loading State
The isLoading should only be false when all fonts (from the current fontData) are successfully loaded.
We use Promise.allSettled() to wait for all promises to resolve or reject.
After all promises settle, we check if all fonts are in the loaded set.
Avoid Duplicate Requests
A Set<string> is used in a ref to track which fonts have already been loaded.
Fonts are only added to the loaded set after they are successfully loaded.
Responsive to Font Changes
The hook re-evaluates the font data on each render and triggers new load operations when needed.
Minimal & Clean
Removed unnecessary complexity, such as nir (a wrapped version of loadFont) and debug logging.
Simplified logic for collecting and loading fonts.
✅ Refactored Code
import { useState, useEffect, useRef } from 'react';
import { retryPromise } from '/utils/retryPromise';
import { FontGroup } from '/Steps/Fonts/data/fontData';
interface Props {
fontData: Array<FontGroup>;
loadFont: (fontFamily: string) => Promise<void>;
}
interface Output {
isLoading: boolean;
hasError: boolean;
}
function useLoadFonts({ fontData, loadFont }: Props): Output {
const [isLoading, setIsLoading] = useState(true);
const [hasError, setHasError] = useState(false);
const loaded = useRef(new Set<string>());
useEffect(() => {
// Collect all font families from fontData
const fonts = fontData.flatMap(({ fonts }) =>
fonts.flatMap(fontPack => [fontPack.headerFontFamily, fontPack.bodyFontFamily])
);
// Find fonts that need to be loaded
const toLoad = fonts.filter(f => !loaded.current.has(f));
if (!toLoad.length) {
// No new fonts to load; check if all fonts are already loaded
const allLoaded = fonts.every(f => loaded.current.has(f));
setIsLoading(!allLoaded);
return;
}
// Create promises for each font to load
const promises = toLoad.map(font => {
return retryPromise(() => loadFont(font))
.then(() => {
loaded.current.add(font); // Only add to loaded set on success
})
.catch(() => {
setHasError(true); // Set error state on any failure
});
});
// Wait for all promises to settle
Promise.allSettled(promises).then(() => {
const allLoaded = fonts.every(f => loaded.current.has(f));
setIsLoading(!allLoaded);
});
}, [fontData, loadFont]);
return { isLoading, hasError };
}
export default useLoadFonts;
Font Collection:
We flatten the fontData into a single list of all headerFontFamily and bodyFontFamily values.
Font Filtering: toLoad contains only those fonts that haven't been previously loaded (i.e., not in the loaded set).
Promise Creation:
For each font in toLoad, we create a retryPromise around loadFont.
On success, the font is added to loaded.current.
On failure, hasError is set to true.
Final State Update:
After all promises settle, we check whether all fonts (from the current fontData) have been loaded.
This ensures isLoading is only false when all fonts are loaded.
🧪 Edge Case Handling
Empty fontData:
If fontData is empty, fonts is an empty array, and isLoading is set to false immediately.
Font Already Loaded:
Fonts already in loaded.current are skipped, preventing duplicate requests.
Font Load Failure:
If any font fails to load, hasError is set to true, and isLoading remains true until all fonts are successfully loaded.
🔁 Performance Considerations
Re-renders:
The useEffect runs only when fontData or loadFont changes, which is efficient.
State Updates: isLoading and hasError are updated only once per fontData change, reducing unnecessary re-renders.
✅ Conclusion
This version of useLoadFonts is:
Accurate: Ensures isLoading is only false when all fonts are truly loaded.
Efficient: Avoids duplicate requests using a Set.
Responsive: Reacts to changes in fontData.
Clean: Minimal and readable, avoiding unnecessary abstractions.