Class component for state, functional for children?

Hello.

I’m doing the React Course. I’m up to lecture React: Pass State as Props to Child Components.

My question: would it be a good practice to have the (stateful) Parent component as a Class and all the child components as functional components?

The code is shorter and I can’t quite see the point of having all the children as class components (if they are not setting state themselves)?

e.g. is this (both class components):

class Parent extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: "Chris",
    }
  }
  render() {
    return (
      <div>
        <Child name={this.state.name} />
      </div>
    )
  }
}

class Child extends Component {
  constructor(props){
    super(props)
  }
  
  render(){
    return(
      <h1>{this.props.name}</h1>
    )
  }
}

better than this (parent is class, child is functional):

class Parent extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: "Chris",
    }
  }
  render() {
    return (
      <div>
        <Child name={this.state.name} />
      </div>
    )
  }
}


function Child(props) {
   return(
    <h1>{props.name}</h1>
   )
}
1 Like

You are right. Only use class based components if you want to have state. Otherwise make them “dumb” components -> functions! :slight_smile:

With hooks, you don’t even need class components for state now.

Thanks - good to know my instincts were right :slight_smile:

1 Like

Sounds interesting - will get to that once I’ve covered the basics :slight_smile: