Would presentational components ever need state?


#1

Question

Would presentational components ever need state?

Answer

As a best practice, a presentational component should be only for display purposes, if we start needing to implement state on that component as well, then it is time to revise it and break down its functionality, it might need to be broken down into smaller presentational components. for example, we have a calculator app, and our presentational component is a calculator display:

import React, { Component } from 'react';

class Display extends Component {
  constructor(prop){
    super(props)
  }

  render(){
    return(<div>{ this.props.number }</div>)
  }
}

export default Display;

Now, what if we want to implement a few interactive buttons on the display because our calculator is fancy and has a touchscreen.

So instead of filling it all in, we can create a new presentational component:

import React, { Component } from 'react';
import Display from './Display';

const screens = ['calc', 'clock', 'weather']
class TouchScreen extends Component {

  constructor(prop){
    super(props)
    this.state = {
      typeOfScreen: 'calc',
      number: 0,
      time: '';
      temp: ''
    }
  }
  
  ...

  renderType(){
    switch(this.state.typeOfScreen){
      case 'calc':
        return(<Display value={this.state.number}/>);
        break;
     case 'clock':
        return(<Display value={this.state.time}/>);
        break;
     case 'weather':
        return(<Display value={this.state.temp}/>);
        break;
    }
  }

  render(){
    return(renderType())
  }
}

export default Display;

Now, the Display component will stay as a display and we can change what is display in it based on type, so we can keep our presentational component stateless.