Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!