Revisited: setState()
Understand how to use the functional form of React's setState to update state based on previous state or props. Discover why this approach prevents bugs caused by asynchronous updates and improves code clarity and testability. Learn to refactor your setState calls and create higher-order functions for better state management in React class components.
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.
But setState() doesn’t take only an object. In its second version, you can pass a function to update the state.
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() ...