Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Created November 8, 2022 15:03
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 lancejpollard/d70223d8ca1691c953dd06c21a3a907f to your computer and use it in GitHub Desktop.
Save lancejpollard/d70223d8ca1691c953dd06c21a3a907f to your computer and use it in GitHub Desktop.
FontObserver React Hook (to prevent FOUC)
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