Stateful components and life cycle methods

React components can manage their own state and update only when the state has changed. Stateful React components are written using ES6 classes:

class Example extends React.Component { 
   render() { 
      <span>This is an example</span> 
   } 
} 

React class components have a state instance property to access their internal state and a props property to access properties passed to the component:

class Example extends React.Component {  
    state = { title: null } 
    render() { 
        return ( 
            <React.Fragment>  
                <span>{this.props.title}</span>  
                <span>{this.state.title}</span>  
            </React.Fragment>  
        ) 
    } 
} 

And their state can be mutated by using the setState instance method:

class Example extends React.Component { state = { title: "Example", ...

Get MERN Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.