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

240
Vistas
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 Respuestas
Responde la pregunta

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