React ยท Chapter 26 of 42

Class vs Function Components

React originally used class components with lifecycle methods like `componentDidMount`. Modern React strongly favors function components combined with hooks, which are simpler and more concise.

Class components still work and are found in older codebases, but new code should use function components.

Class components

Class components extend `React.Component`, define state in `this.state`, and use lifecycle methods like `componentDidMount`, `componentDidUpdate`, `componentWillUnmount`.

Function components with hooks

Function components use hooks (`useState`, `useEffect`) to achieve the same capabilities with less boilerplate and easier logic reuse.

Example 1 (jsx)
// Class component
class Hello extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

// Equivalent function component
function Hello({ name }) {
  return <h1>Hello, {name}</h1>;
}
Output
Hello, Ada (both render identically)

Both components render the same output; the function version is simpler.

Key points

  • Class components use this.state and lifecycle methods.
  • Function components use hooks for state and side effects.
  • Modern React code should prefer function components.
  • Error boundaries are one of the few things still requiring a class.
๐Ÿ’ก Note: You'll still encounter class components in legacy code, so it's worth recognizing their syntax.

๐Ÿ“ Quick Quiz

1. What do class components extend?

2. What do modern function components use for state?

3. What is one thing that still requires a class component?