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

88
Visualizações
React useEffect hook toggle issue

I confused myself on how useEffect works in React. The following code works, but in the opposite way as it is intended. Instead of the background picture appearing after you check the checkbox, it appears when the checkbox isn't checked, and dissapears when it is checked.

function Beautifier() {
  const [isBeautiful, setIsBeautiful] = React.useState(false);

  React.useEffect(
    function toggleBackground(shouldShow) {
      document.body.classList.toggle('with-bg', shouldShow);
    }
  );
  
function handleChange() {
  setIsBeautiful(!isBeautiful);
} 

  return (
    <label>
      <input type="checkbox" onChange={handleChange} />
      Turn on pretty background
    </label>
  );
}

ReactDOM.render((
  <Beautifier />
), document.querySelector('#root'));

I am pretty sure my issue is that I am lacking a return() => in the useEffect hook, but all the things I could think off did not resolve the issue/or broke the function. Not adding CSS, as that part is working fine.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I appears you've declared toggleBackground twice and don't invoke it. You are also missing a dependency array on the useEffect. I'm assuming you meant to actually call toggleBackground in the useEffect callback. Use the isBeautiful state as the dependency, and pass this to the toggleBackground function.

React.useEffect(() => {
  toggleBackground(isBeautiful);
}, [isBeautiful]);

You should also use a functional state update to toggle the isBeautiful state.

function handleChange() {
  setIsBeautiful(isBeautiful => !isBeautiful);
} 
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