Good news: setState can take a callback!

While working on my React final project, I am changing state many, many (too many ?) times. I got stuck because of async issues and after some research discovered that setState() can take an optional callback as its second argument. So let’s look into that !

"setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.” — from the Official React Documentation

So if you want to access the updated state right after changing it, you have two options: componentDidUpdate() or a setState callback.

setState() with a callback

The callback is fired with the updated state. It can be compared to .then after a fetch request: it waits for the first action to be finished, before starting the next one.

The setState callback will fire no matter whatshouldComponentUpdate() returns, meaning it will fire event when state hasn’t been changed. For that reason, official documentation recommends using lifecycle methods (specifically componentDidUpdate()) for such logic.

)

Lili Ouaknin Felsen

Written by

Software Engineer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade