Creating your first stateful React component
Stateful components are the most appropriate place for your application to handle the interaction logic and manage states. They make it easier for you to reason about how your application works. This reasoning plays a key role in building maintainable web applications.
React stores the component's state in a this.state
object. We assign the initial value of this.state
as a public class field of the Component
class:
class ReactClass extends React.Component { state = { isHidden: false }; render() { const { isHidden } = this.state; if (isHidden) { return null; } return ( <h1 className="header">React Component</h1> ); } }
Now, { isHidden: false }
is the initial state of our React component and our user interface. Notice that in our render()
method, we're now destructuring the isHidden
property from this.state
instead of this.props
.
Earlier in this chapter, you learned...