There’s something odd about all of this.
Look again at Toggle.js.
When a user clicks on the
.changeColor() method is called. Take a look at
this.setState(), which updates
this.state.color. However, even if
this.state.color is updated from
yellow, that alone shouldn’t be enough to make the screen’s color change!
The screen’s color doesn’t change until
Inside of the render function, it’s this line:
that changes a virtual DOM object’s color to the new
this.state.color, eventually causing a change in the screen.
If you call
.changeColor(), shouldn’t you then also have to call
.changeColor() only makes it so that, the next time that you render, the color will be different. Why can you see the new background right away, if you haven’t re-rendered the component?
Here’s why: Any time that you call this.setState(), this.setState() AUTOMATICALLY calls .render() as soon as the state has changed.
this.setState() as actually being two things:
this.setState(), immediately followed by
That is why you can’t call
this.setState() from inside of the
this.setState() automatically calls
this.setState(), then an infinite loop is created.