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