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

241
Visualizações
Toggling boolean state in React Hooks

When I run the following code and clicking the button, I manage to trigger the useEffect function:

const { useState, useEffect } = React;

const Example = () => {
  const [bool, setBool] = useState(false);

  useEffect(() => {
    console.log(bool);
  }, [bool]);

  return (
    <button
      type='button'
      onClick={() => {
        setBool(!bool);
        setBool(!bool);
      }}
    >
      Check
    </button>
  );
};

ReactDOM.render(
  <Example />,
  root
)
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

However, when I write:

const { useState, useEffect } = React;

const Example = () => {
  const [bool, setBool] = useState(false);

  useEffect(() => {
    console.log(bool);
  }, [bool]);

  return (
    <button
      type='button'
      onClick={() => {
        setBool(true);
        setBool(false);
      }}
    >
      Check
    </button>
  );
};

ReactDOM.render(
  <Example />,
  root
)
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

I understand that the useEffect function isn't triggered as setBool is async, and React merges these changes so the final state wasn't changed (bool remains false).

My question is, why React is unable to detect it in the case of !bool & !bool that I showed up.

Thanks

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

0

In the first case, you are taking the current value of bool (whatever that value may be) and negating it before setting it in the state. As a result, state is changed, so useEffect is triggered.

In the second case, you are providing a hard-coded value. If the value of bool is already false, then setBool(false) won't have any affect on the state; as a result, useEffect won't be triggered.

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