'React toggle theme and save it to localStorage and also toggling classes to the html body tag

Please take a look at my code the toggle button is working completely fine but I also want to save the toggle state to localStorage I have tried it so many times before especially with Vanilla JS but I'm so new to React and every time I try to save the value to localStorage with useEffect hook it just toggles between the states really quickly and then reverts and to the original state. Any suggestions will be highly appreciated.

Also here's the repo: https://github.com/AbidAlWassie/React-Portfolio-main

and here's the fully deployed site: https://abidalwassie.github.io/React-Portfolio-main/


import React from 'react'
import { useState, useEffect } from 'react'
import { MdOutlineDarkMode } from 'react-icons/md'

const Navbar = () => {

  const [scheme, setScheme] = useState(false);

  const [toggle, setToggle] = useState(false);

  useEffect(() => {
    document.body.classList.toggle('light', scheme);
  }, [scheme]);

  useEffect(() => {
    const navbar = document.getElementById("navbar");
      navbar.classList.toggle("open", toggle);
  }, [toggle]);


  return (
    <nav className='navbar' id='navbar'>
      <div className="container flex justify-between items-center mx-auto text-center">

      <div className='my-logo'>
        <div className='circle'><span className="firstLetter">A</span><div className="half-circle"></div></div>
        <span className="otherLetters" draggable="false">bid</span>
      </div>
    
      <div className="nav-holder">
        <ul className='nav-list'>
        {[
          'home',
          'about',
          'skills',
          'services',
          'work',
          'contact'
        ].map((item) => (
            <li className='nav-link' key={`link-${item}`}>
              <a href={`#${item}`} draggable="false"> {item}</a>
            </li>
          ))}
        </ul>
      </div>
      <button className='toggleBtn' id='toggleBtn' onClick={()=> setScheme(!scheme) }>
        <MdOutlineDarkMode/>
      </button>

      <div className='menuBtn hamburger' onClick={()=> setToggle(!toggle) }>
        <div className="bar"></div>
        <div className="bar"></div>
        <div className="bar"></div>
      </div>

    </div>
    </nav>
    
  )
}

export default Navbar



Solution 1:[1]

You have to set scheme value in useState from localStorage to initialize next time, Add below code on top,

const localTheme = JSON.parse(localStorage.getItem('key_name')) || false;
const [scheme, setScheme] = useState(localTheme);

And need to store on useEffect in localStorage

useEffect(() => {
  document.body.classList.toggle('light', scheme);
  localStorage.setItem('key_name',scheme); 
}, [scheme]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikhil Vagadiya