Components

Function components

Function components have props — but no state or lifecycle methods.

Cough — that’s not entirely true anymore. Hooks were added in React 16.8.x so function components can access features like state.

a.k.a. presentational components
a.k.a. simple components
a.k.a. dumb components

Because they don’t know the origin of the props they receive.

Example

function Welcome (props) {
    return <h1>Hello, {props.name}</h1>;
}

Class components

Class components have props, state, and lifecycle methods. They’re almost always the parent of simple Components.

a.k.a. container components
a.k.a. smart components

Because they’re aware of the application as a whole.

Example

class Welcome extends React.Component {
    render() {
        return <h1>Hello, {this.props.name}</h1>;
    }
}

This slightly more complex example uses state and lifecycle methods:

Articles

CSS Tricks — Container components

This code is outdated, but the concepts are applicable.

  • Components that both fetch data and render are tightly-coupled.
  • Refactoring as two Components makes this more DRY and reusable.
  • Container Components (smart) source data and deal with state.
  • Presentational Components (dumb) receive state as props and render the view.

Dan Abramov — How are function components different from classes

The difference is subtle and confusing. Read it twice. Try to demos to see the effect.

  • Function components capture the rendered values.
  • Class components using this can introduce bugs because this is mutable.

Dan Abramov — Why do we write super(props)?

  • super() refers to the parent class constructor(i.e. React.Component).
  • You can’t use this in a component’s constructor until after you’ve called the parent constructor.
  • Writing super(props) assigns props on the component’s instance, so this.props can be used in the constructor.