I'm new to React and just practicing useEffect hooks after going through a hooks course.
I have a button to toggle state change of arrowState.
export default function Test() {
const [arrowState, setArrowState] = useState(true);
const [arrowChange, setArrowChange] = useState(false);
const toggleButton = () => {
return setArrowState((arrowState) => {
return !arrowState;
});
};
return (
<>
<div>
<button
type="button"
onClick={toggleButton}
>
Toggle Arrow
</button>
</div>
{arrowChange && <Notific />}
</>
);
}
Then I have a useEffect hook which changes state of arrowChange. Also have a timeout to change state of arrowChange to false - thereby auto-disappearing the button after 2 secs.
useEffect(() => {
console.log("first line of useEffect.arrowChange is ", arrowChange);
setArrowChange(true);
console.log(
"immediately after setArrowChange to true. arrowChange is ",
arrowChange
);
setTimeout(() => {
console.log("first line of setTimeOut. arrowChange is ", arrowChange);
arrowChange && setArrowChange(false);
}, 1000);
return () => {
console.log("cleaning up arrowchange. arrowChange is ", arrowChange);
setArrowChange(false);
};
}, [arrowState]);
Based on it, I'm displaying another button with a message.
function Notific() {
return (
<button
type="button"
onClick={() => setArrowChange(false)}
>
Arrow state has been changed
</button>
);
}
As you can see, I'm logging some messages to see the effect. I'm surprised to see that even after setting arrowChange to true at the beginning of useEffect hook, it's still showing false at alternate events.
Check these console logs:
cleaning up arrowchange. arrowChange is false
Test.js:57 first line of useEffect.arrowChange is true
Test.js:59 immediately after setArrowChange to true. arrowChange is true
Test.js:65 first line of setTimeOut. arrowChange is true
Test.js:70 cleaning up arrowchange. arrowChange is true
Test.js:57 first line of useEffect.arrowChange is false
Test.js:59 immediately after setArrowChange to true. arrowChange is false
Test.js:65 first line of setTimeOut. arrowChange is false
Test.js:70 cleaning up arrowchange. arrowChange is false
Test.js:57 first line of useEffect.arrowChange is true
Test.js:59 immediately after setArrowChange to true. arrowChange is true
Test.js:65 first line of setTimeOut. arrowChange is true
Test.js:70 cleaning up arrowchange. arrowChange is true
Test.js:57 first line of useEffect.arrowChange is false
Test.js:59 immediately after setArrowChange to true. arrowChange is false
Test.js:65 first line of setTimeOut. arrowChange is false
Test.js:70 cleaning up arrowchange. arrowChange is false
Test.js:57 first line of useEffect.arrowChange is true
Test.js:59 immediately after setArrowChange to true. arrowChange is true
Test.js:65 first line of setTimeOut. arrowChange is true