Understanding React setState() (Callback, Async-Await and Promises)

React setState() is a function that mutates the component state (i.e this.state). The React docs recommends using the setState() method instead of directly set state values i.e doing something like this.state.someState = 'someValue' (except in the constructor) since using the last approach doesn't guarantee React knows about the current updates in state, so it can properly re-render itself, which may lead to some inconsistent results.

Components state is a corner concept in React (alongside the component concept itself) and It’s simply a variable (Plain Old JavaScript Object) that stores internal information of a given component.

Outside a constructor, you need to use setState() to update your component state. This method takes a JavaScript object that gets merged into the component state but that’s not the only thing that you need to know about setState() in order to correctly and effectively use in your application. Here is a list of things that you should know:

  • setState() is Asynchronous
  • setState() Can Have a Function as A Parameter Instead of An Object
  • setState() Can Have a Callback Function

comments powered by Disqus