5.2: setState
Last updated
Last updated
An ultra important method in React is setState()
. Remember that state is all about interactivity and driven by changes in the DOM. We set the initial state in the constructor with this.state
, but what about when something changes? For that, the primary method you would use to update the user interface in response to event handlers and server responses is setState()
.
Take a minute to read about setState(). It is one of the most used tools for a React developer.
For right now, we just need to know that setState()
is the catalyst in the render method being fired if the DOM has changed and an event has taken place.
Let's play around with setState()
by building a traditional counter. Replace the code in ClassComponentDemo
with the following:
Later on we'll show you a way to see the order of events in a component, as each one has its own lifecycle method. console.log
statements are still very useful in understanding an application. Below, we added a few in the increment()
function and the render()
function. Go ahead and add those methods and run the app.
As you click the button, you should see the the incrementCount method fires, and then the render() method fires. Looking at this might make you wonder about bigger enterprise applications and just how many times the render function gets fired off. Also, start thinking about how each class component has its own internal render()
method. This starts to get both extremely complex and extremely fun.
Let's go on to a