I am using react to switch between light and dark mode in my website . I also want the theme to persist using localstorage . The problem is that while clicking on switch to toggle the theme the corresponding localstorage theme value does not update. I know that state updates are asynchronous but I want to fix this .
My code:
const [darkMode , setDarkMode] = useState(false);
//change theme
const toggleTheme = ()=>{
setDarkMode(!darkMode);
const root = window.document.documentElement;
if(localStorage.getItem("isDark")=== null){
localStorage.setItem("isDark",darkMode);
}else{
localStorage.setItem("isDark",darkMode);
}
root.classList.toggle('dark');
}
I tried using async await but the result was the same .