In the code below, how do I make the value of status variable change immediately after setStatus(!status)
?
You can't make state to change immediately as changing state is async.
I would even prefer that the changes of this variable do not trigger a render), would it be bad practice to not use useEffect
at all and make status a "normal" variable instead, assigned like status = true?
First, check what are the use cases for useEffect
.
About making a "normal" variable instead, its indeed a bad practice:
const Component = () => {
let variable = ...;
return <>...</>
}
That's because, on every render, such variables will re-assigned (because the body of the function component executed on every render). Usually, it is not the desired behavior.
Instead, you want to use a reference with useRef
. See what is the difference between useRef
and a variable.
Changing the reference value won't trigger a render, therefore won't update the UI.