I’m trying to keep state on a refresh in my React application using this code:
const [darkMode, setDarkMode] = useState(localStorage.getItem('darkMode') || false);
const [mode, setMode] = useState({bg: 'light', variant: 'light'})
const toggleDarkMode = () => {
if (darkMode === true) {
setMode({bg: 'light', variant: 'light'})
setDarkMode(false);
localStorage.setItem("darkMode", false );
} else {
setMode({bg: 'dark', variant: 'dark'})
setDarkMode(true);
localStorage.setItem("darkMode", true );
}
};
toggleDarkMode
is called by a button onChange
event.
But when I refresh or go to a different URL the state is lost. It’s important to keep this state as its for the dark / light mode.
I have tried calling local storage using window.localStorage
and tried to place it in useEffect
so it would update constantly but the state still seems to be lost. I’ve also tried parsing it as JSON which a lot of tutorials recommend but that also doesn’t seem to work.
Occasionly on a new page instance I’ll get the error about bg cannot be undefined, which makes me think the state isn’t being stored.
Why is the state being lost and is there a better / more efficient way to do this?