Ryan Kegerreis

setState Takes A Callback

May 17, 2020

You’re probably familiar with setState if you’ve programmed even a few React components. It’s a standby function that you will use all the time. But it has a trick up its sleeves. Read the docs kids.

setState takes a callback.

setState(updater, callback)

Now most functions that take callbacks might not be super exciting. But this one is special. When you pass a function into the callback argument of setState, it is guaranteed to run after the state changes.

With React managing state can be tricky when it comes to timing, and while there are many ways to handle the flow of state in an application, this is one every React developer should be aware of.


Written by Ryan Matthew Kegerreis.