Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
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

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda