title: How can I make the website theme persists on refresh in React?
body: <p>I'm currently working in a weather forecast website and I'm trying to apply a theme toggler. I have already set up the functionality, but the chosen theme does not persist when the page is refreshed. Could anyone point out what I'm missing? The console.log shows that the theme inside localStorage changes when I click the theme toggler.</p>
  <pre><code>import { WeatherApi } from &quot;./pages/home/weather-api&quot;;
  import '../src/App.scss'
  import { createContext, useEffect, useState } from &quot;react&quot;;
  import ReactSwitch from &quot;react-switch&quot;;
  
  export const ThemeContext = createContext({})
  
  function App() {
  
    const [theme, setTheme] = useState&lt;string&gt;(localStorage.getItem('theme') || 'light')
  
    useEffect(() =&gt; {
  
      const localTheme = localStorage.getItem(theme)
      console.log(localTheme)
  
      if (!localTheme) {
        setTheme(&quot;light&quot;)
      }
  
      if (localTheme) {
        if (localTheme === 'light') {
          setTheme('light')
          localStorage.setItem('theme', theme)
          console.log(localStorage)
        }
  
        if (localTheme === 'dark') {
          setTheme('dark')
          localStorage.setItem('theme', theme)
          console.log(localStorage)
        }
      }
    },[theme])
  
    const toggleTheme = () =&gt; {
      setTheme((currentTheme: any) =&gt; (currentTheme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;))
    }
  
    return (
      &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;
        &lt;div className=&quot;App&quot; id={theme}&gt;
          &lt;WeatherApi /&gt;
          &lt;div className=&quot;switch&quot;&gt;
            &lt;label&gt;{theme === &quot;light&quot; ? &quot;Light mode&quot; : &quot;Dark mode&quot;}&lt;/label&gt;
            &lt;ReactSwitch onChange={toggleTheme} checked={theme === &quot;dark&quot;} /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/ThemeContext.Provider&gt;
    )
  
  }
  
  export default App;
  </code></pre>