Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda