setState wont update state. Basic React Question
Answered
Virginia's Warbler posted this in #help-forum
Virginia's WarblerOP
const [muted, setMuted] = useState(false);
const clickHandlerFunction = () => {
console.log('muted before', muted);
setMuted(!muted);
console.log('muted after', muted);
}
Why is
muted
false
both before and after setMuted
?Answered by Asian black bear
useEffect(() => {
// do something when muted has been updated by React
}, [muted])
7 Replies
@Virginia's Warbler
const [muted, setMuted] = useState(false);
const clickHandlerFunction = () => {
console.log('muted before', muted);
setMuted(!muted);
console.log('muted after', muted);
}
Why is `muted` `false` both before and after `setMuted`?
state updates are async which means they don't happen immediately
react will update the statement only when it has time to do so
Asian black bear
Either write your code following the
setMuted
call in such a way to assume its value or use an effect that listens to actual changes whenever React is done updating. Additionally, use the syntax setMuted(value => !value)
instead of self-referencing the original state value as this can cause unexpected behaviour when you least expect it.Virginia's WarblerOP
use the syntax setMuted(value => !value) instead of self-referencing the original state value as this can cause unexpected behaviour when you least expect it.This part, I understand. Thank you
@Asian black bear Either write your code following the `setMuted` call in such a way to assume its value or use an effect that listens to actual changes whenever React is done updating. Additionally, use the syntax `setMuted(value => !value)` instead of self-referencing the original state value as this can cause unexpected behaviour when you least expect it.
Virginia's WarblerOP
But for this part
Either write your code following the setMuted call in such a way to assume its value or use an effect that listens to actual changes whenever React is done updating.Can you please give an example. Not sure exactly how its done
Asian black bear
useEffect(() => {
// do something when muted has been updated by React
}, [muted])
Answer
Virginia's WarblerOP
Thank you, it helped