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
My code compiles with no warnings or errors, and my useEffect function is in the top-level of my App component.
CodePudding user response:
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)
}
}, [])