Home > Mobile >  How to save darkMode in local storage in React?
How to save darkMode in local storage in React?

Time:03-29

I want to save in local storage what theme the user has chosen - light or dark, so that when the page refreshes the theme is still current with the user's choice. I tried using the useEffect hook for this, but I am probably doing something wrong. I have included the code below:

function App() {
// Theme
    const [theme, setTheme] = useState('light');
    const checkTheme = () => theme === 'light' ? setTheme('dark') : setTheme('light') ;

// Amount of Portions
const [amountOfPortions , setAmountOfPortions] = useState(1);

const updateAmountOfPortions = (dataFromChild) => {
    setAmountOfPortions(dataFromChild);
};

return (
    <div className={`app wrapper app__bgc--${theme}`}>
        <Switch onChange={checkTheme} color="primary"/>
        <MainCard update={updateAmountOfPortions}/>
        <Recipe value={amountOfPortions}/>
    </div>
    
)};

CodePudding user response:

You are just setting state which will be lost once the component refreshes

You need to write a function using the localStorage api. something like:

const setThemeInStorage = (theme) => {
   localStorage.setItem('theme', theme)
}

then call it like

setThemeInStorage('light')

and retrieve it like so:

const getThemeInStorage = () => {
   localStorage.getItem('theme') // returns 'light' in this case
}

if you want to run this code instantly do

const theme = getThemeInStorage() then theme is the value of localStorage

CodePudding user response:

The easiest way is using a custom hook like useLocalStorage. If you don't want to use the hook, they still have the code that implements the localStorage writing/reading part with comments explaining how they do it so that you can do it in a different way (though I can't think why you would).

  • Related