Reputation: 31
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
Upvotes: 2
Views: 2977
Reputation: 29282
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.
Upvotes: 3