Chapter 4. Making React interactive with states

 

This chapter covers

  • Understanding React component states
  • Working with states
  • States versus properties
  • Stateful versus stateless components

If you read only one chapter in this book, this should be it! Without states, your React components are just glorified static templates. I hope you’re as excited as I am, because understanding the concepts in this chapter will allow you to build much more interesting applications.

Imagine that you’re building an autocomplete input field (see figure 4.1). When you type in it, you want to make a request to the server to fetch information about matches to show on the web page. So far, you’ve worked with properties, and you’ve learned that by changing properties, you can get different views. But properties can’t change in the context of the current component, because they’re passed on this component’s creation.

Figure 4.1. The react-autocomplete component in action

To put it another way, properties are immutable in the current component, meaning you don’t change properties in this component unless you re-create the component by passing new values from a parent (figure 4.2). But you must store the information you receive from the server somewhere and then display the new list of matches in the view. How do you update the view if the properties are unchangeable?

Figure 4.2. We need another data type that’s mutable in the component to make the view change.

4.1. What are React component states?

 
 

4.2. Working with states

 
 

4.3. States and properties

 
 
 
 

4.4. Stateless components

 
 

4.5. Stateful vs. stateless components

 
 
 
 

4.6. Quiz

 
 

4.7. Summary

 
 
 

4.8. Quiz answers

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest