Created
November 8, 2022 15:03
-
-
Save lancejpollard/d70223d8ca1691c953dd06c21a3a907f to your computer and use it in GitHub Desktop.
FontObserver React Hook (to prevent FOUC)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react' | |
import FontFaceObserver from 'fontfaceobserver' | |
export default function useFonts(allFonts, selectedFonts) { | |
const [isVisible, setIsVisible] = useState(false) | |
useEffect(() => { | |
const fonts = selectedFonts.length | |
? selectedFonts.map(name => allFonts[name]) | |
: Object.values(allFonts) | |
Promise.all(fonts.map(([_, testString, fontName]) => { | |
const font = new FontFaceObserver(fontName) | |
return font.load(testString, 30000) | |
})) | |
.then(() => setIsVisible(true)) | |
}, [selectedFonts.join(':')]) | |
return isVisible | |
} | |
// then elsewhere: | |
export default { | |
'latin': ['/font/screen/latin.otf', 'IEAOU', 'Latin'], | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment