[Next.js 13] How to fix FOUC on Tailwind Dark Mode
Unanswered
Siamese posted this in #help-forum
SiameseOP
const [darkMode, setDarkMode] = useState(false)
useEffect(() => {
const darkMode = localStorage.theme === 'dark' || (!('theme' in localStorage))
setDarkMode(darkMode)
if (darkMode) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
}, [])
const toggleDarkMode = () => {
if (localStorage.theme === 'dark') {
localStorage.theme = 'light'
document.documentElement.classList.remove('dark')
setDarkMode(false)
} else {
localStorage.theme = 'dark'
document.documentElement.classList.add('dark')
setDarkMode(true)
}
}10 Replies
useEffect only runs after the page is hydrated, so there will be a delay after the page is painted by the browser and this code runsto avoid a FOUC you need to run this logic outside react itself, there are some libraries that allows you to do it easily: https://github.com/pacocoursey/next-themes/
SiameseOP
i checked it and i have some concerns (just personal preferences)
can i make do with loading page/ delaying preview?
can i make do with loading page/ delaying preview?
yes, but that would be pretty bad since it will considerably lower your core vital metrics, specifically the FCP
so you will trade one problem with other
if you don't like the library for any reason you can implement the logic by yourself
here is an example without any libraries (this is a gatsby app so you will need to adapt it to next): https://github.com/gaearon/overreacted.io/blob/2e810e189ba30c9825b989c3cf678a491ee2c1c3/src/html.js#L18-L51
@Rafael Almeida if you don't like the library for any reason you can implement the logic by yourself
SiameseOP
i think its because i don't know much yet haha
thanks for the resources!! v helpful
also really appreciate the explanations, i understand it better now