How can I know when something should be stateful or stateless?


#1

Question

How can I know when something should be stateful or stateless?

Answer

When talking about state, we want the least amount as possible, therefore we want to keep as many components stateless as we can. To gauge when it should be the case and when we will need to introduce some state is mainly related to the component’s interaction. For example, a form component will need state to keep the information filled through the inputs and be able to manipulate it:

class FormComponent extends React.Component{
  constructor(){
    this.state = {
      name:' ',
      address: '',
      age: 0,
      dob: '',
    }
  }

  handleChange = (e) => {
     this.setState({e.target.name: e.target.value});
  }

  handleSubmit = (e) => {
    e.preventDefault(); // always use to prevent re-rendering of page
    ...
  }

  render(){
    return(
      <form onSubmit ={ this.handleChange }>
        <label>
          Name:
        <input name = 'name' value={this.state.name} type='text' onChange={this.handleChange}/>
        </label>
         ...
        <input type="submit" value="Submit" />
      </form>
    )
  }

but for example if your component is only displaying values, then it is completely free to become an stateless component:

class UserDisplay extends React.component{
  constructor(props){
    super(props)
  }

  render(){
    return(
      <div>
         <h1> Welcome {this.props.name} </h1>
         <br/>
         <div>
           <h3> DOB </h3>
           <p> {this.props.dob}</p>
           ... {/*so many ways to display this information*/}
         </div>
      </div>
    )
  }
}

At the end it is up to our best judgement based on the interaction of the app to decide which components need to be stateful or stateless, that said, all our intentions should be to keep as many stateless components as possible since it makes it easier for us to debug, edit, and reason with. If by any reason the app will require a lot of state, I would recommend to look at state management libraries like Redux, if you want to learn about it here’s an article from the Codecademy account on Medium which also talks about react router, a rendering manager for components which also gives them browser routes as if they were different pages while being a single page application.