questions about setState callback in Offical Doc

(Daisy Wong) #1

I am confusing why the the doc says:

< The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

why they recommand to use componentDidUpdate instead of the callback to get the latest state value?

(Michae Gichia) #2

Hey, please counter check the documentation again. To paraphrase what the documentation state, “This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.”

Componentdidupdate is invoked immediately when update occurs so you can compare prevstate with state and update accordingly.

The setState callback guarantee that to fire after update has been applied.