Skip to content

Instantly share code, notes, and snippets.

@Rendez
Last active October 6, 2022 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rendez/fb31b0d765a58ab3c962372899cf3f45 to your computer and use it in GitHub Desktop.
Save Rendez/fb31b0d765a58ab3c962372899cf3f45 to your computer and use it in GitHub Desktop.
import {useLayoutEffect, useState} from 'react';
const fontFaces = [
['tangerine', new FontFace('"Tangerine", serif', 'url(https://fonts.googleapis.com/css?family=Tangerine)')]
] as const;
export function useFontsLoaded(types = ['tangerine']) {
const [fontsLoaded, setFontsLoaded] = useState(false);
const depTypes = types.join(' ');
useLayoutEffect(() => {
const typesList = depTypes.split(' ');
Promise.all(
fontFaces.map(([type, fontFace]) => {
if (typesList.includes(type)) {
return fontFace.load();
}
return Promise.resolve();
})
)
.then(() => {
setFontsLoaded(true);
})
.catch((e) => {
console.error('Fonts Loaded Hook: error loading one or more fonts.', e);
});
}, [depTypes]);
return fontsLoaded;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment