In the past, we've been explicitly warned that calling setState({myProperty})
is asynchronous, and the value of this.state.myProperty
is not valid until the callback, or until the next render()
method.
With useState, how do I get the value of the state after explicitly updating it?
How does this work with hooks? As far as I can tell, the setter function of useState
doesn't take a callback, e.g.
const [value, setValue] = useState(0);
setValue(42, () => console.log('hi callback');
doesn't result in the callback being run.
My other workaround in the old world is to hang an instance variable (e.g. this.otherProperty = 42)
on the class, but that doesn't work here, as there is no function instance to reuse (no this
in strict mode).