DEV Community

Discussion on: Toggle Dark Mode in React

Collapse
 
mnunezdm profile image
Miguel Núñez Díaz-Montes

Why are you doing this?

localStorage.getItem('theme') && localStorage.getItem('theme') === 'theme-dark'

And not directly this?

localStorage.getItem('theme') === 'theme-dark'

Collapse
 
abbeyperini profile image
Abbey Perini

"if (localStorage.getItem('theme') && localStorage.getItem('theme') === 'theme-dark')" in keepTheme() is checking if a theme is stored in localStorage before comparing it to a string. It's in the main container's useEffect() and was throwing an error if it didn't exist when written like you suggest. The handleOnClick() in the Toggle component is written the way you suggest because there's always something in localStorage by the time it gets used.

Collapse
 
abbeyperini profile image
Abbey Perini • Edited

Now it occurs to me I could totally refactor it to

if (localStorage.getItem('theme')) {if (localStorage.getItem('theme') === 'theme-dark') {setTheme('theme-dark'); } else if (localStorage.getItem('theme') === 'theme-light') {setTheme('theme-light')

} else {
setTheme('theme-dark')
}
}

ETA: the site and blog have been updated with this refactor