Components
Function components
Function components have props but no state or lifecycle methods.
AKA presentational/simple/dumb components — because they don’t know the origin of the props
they receive.
Cough — Not true anymore. Hooks (added in React 16.8) let function components access features like state, lifecycle, context, and refs.
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.
AKA container/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.
Advanced articles
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 becausethis
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, sothis.props
can be used in the constructor.