Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my conditional statement not working as expected in useEffect hook?

It seems that the if-statement in my useEffect hook is evaluating, even though the condition is false. Why is this happening?

My code:

useEffect(() => {
  console.log(localStorage.getItem("darkMode"))
  if (localStorage.getItem("darkMode")) {
    console.log(localStorage.getItem("darkMode"))
  }
}, [])

The console:
Console showing false twice

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code compiles with no warnings or errors, and my useEffect function is in the top-level of my App component.

>Solution :

The issue is that localStorage.getItem always returns a string (or null if there is no value). Because of that it will always run the code inside the if-block unless the string is empty.
You can either parse the string with JSON.parse or simply check for equality to "true".

useEffect(() => {
  console.log(localStorage.getItem("darkMode"))
  if (localStorage.getItem("darkMode") === "true") {
    console.log(localStorage.getItem("darkMode"))
  }
}, [])

or

useEffect(() => {
  const mode = JSON.parse(localStorage.getItem("darkMode"));
  console.log(mode);
  if (mode) {
    console.log(mode)
  }
}, [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading