DEV Community

Cover image for Dark Mode in React using Hooks

Dark Mode in React using Hooks

Rohit kumar singh on May 12, 2020

Why need Dark Mode ? Because it looks cool 😎 Correct but its not enough. Dark mode is known to save a lot of energy on AMOLED screens. ...
Collapse
 
joeattardi profile image
Joe Attardi

Nice! There is also a media query, prefers-color-scheme, that you can use to automatically detect if the user's operating system is set to dark mode!

developer.mozilla.org/en-US/docs/W...

Collapse
 
rohit1508 profile image
Rohit kumar singh

Correct Joe, I will use that in my next article. But prefers-color-scheme not supported by many of the browsers as of now. so, I thought of going with this approach.

Collapse
 
fomenkogregory profile image
Greg

Nice post! But just a little tip, this expression

  const [isDark, setIsDark] = useState(localStorage.getItem("theme") === "dark" ? true : false)

can be written in a bit cleaner way, if you get rid of ternary operator:

  const [isDark, setIsDark] = useState(localStorage.getItem("theme") === "dark")
Collapse
 
rohit1508 profile image
Rohit kumar singh

Thanks Greg, we can avoid the ternary.
But suppose a case if we didn't get theme from browser's localStorage, then it will throw undefined and assigned to isDark, but yes we can handle that later. To make the article more understandable I made it like that, so I will convey the code more clearly.

Collapse
 
aravindballa profile image
Aravind Balla • Edited

Great write up! I did the same using class names on <body> for my website recently. CSS variables are really powerful.

Collapse
 
rohit1508 profile image
Rohit kumar singh

Thanks Aravind 😊

Collapse
 
gillarohith profile image
Rohith Gilla

Amazing

Collapse
 
rohit1508 profile image
Rohit kumar singh

Thanks Rohith

Collapse
 
guriksolves profile image
Guri-ksolves

Nice one broπŸ‘πŸ‘

Collapse
 
rohit1508 profile image
Rohit kumar singh

thanks πŸ˜€

Collapse
 
waleedd322 profile image
walid • Edited

why we dont need context api or redux here ? should we implement that ? some other examples use context api, but here it works without it, even if we have ten pages, and one button ?