Revisited: setState()
In this chapter we revisit the React setState() method. We learn that setState() is asynchronous and not only takes objects as arguments but also takes functions.
We'll cover the following...
setState()
can take functions as input
So far, we have used React setState()
to manage your internal component state. We can pass an object to the function where it updates partially the local state.
this.setState({ value: 'hello'});
But setState()
doesn’t take only an object. In its second version, you can pass a function to update the state.
this.setState((prevState, props) => {...});
Use cases of functions as input
There is one crucial case where it makes sense to use a function over an object: when you update the state depending on the previous state or props. If you don’t use a function, the local state management can cause bugs. The React setState()
method is asynchronous. React batches setState()
calls and executes them eventually. Sometimes, the previous state or props changes between before we can rely on it in our setState()
...