Capítulo 79 de 116

Chapter 79: Component (legacy class API)

Core Idea

Component is the base class the pre-Hooks class-component API extends — the docs treat class components as a legacy pattern to understand for maintaining existing code, not the recommended way to write new components (function components + Hooks is the modern default).

Key Concepts

  • Legacy status: nearly everything a class component provides has a direct function-component + Hooks equivalent — this.state/this.setStateuseState, componentDidMount/componentDidUpdate/componentWillUnmountuseEffect, and so on. New code should default to function components.
  • Lifecycle methods: constructor (initialize this.state), render() (return JSX, must stay pure like a function component's body), componentDidMount/componentDidUpdate/componentWillUnmount (side effects, roughly mapping to Ch 36's Effect model but split across three separate methods instead of one Effect + cleanup).
  • One thing class components still uniquely provide: error boundaries. static getDerivedStateFromError() and componentDidCatch() have no Hook equivalent — a component that needs to catch rendering errors in its subtree currently must be a class component (see the error-boundaries ESLint rule, Ch 47, which checks this pattern is implemented correctly).
  • this binding gotchas: class methods used as event handlers need explicit binding (constructor .bind(this), or class-field arrow-function syntax) to have the correct this when called — a category of bug that doesn't exist in function components/Hooks at all.

Key Takeaways

  1. Default to function components with Hooks for all new code — the docs treat classes as a maintenance/legacy topic, not a parallel first-class option.
  2. Error boundaries remain the one genuine reason to still write a class component in modern React.
  3. this-binding bugs are a class-component-specific footgun that Hooks-based components simply don't have.

Connects To

  • Ch 21 (State: A Component's Memory) and Ch 36 (Synchronizing with Effects): the Hook equivalents of this.state/lifecycle methods.
  • Ch 89 (PureComponent): the shallow-prop-comparison optimization variant of this base class.