Class Components Overview
While functional components with hooks are now the standard, understanding class components is valuable for maintaining legacy code and understanding React’s evolution.Creating a Class Component
Class components extendReact.Component and must have a render() method:
Working with State
State is initialized in the constructor and updated withsetState():
Use
.bind(this) or arrow functions to ensure methods have access to the component instance.Lifecycle Methods
Class components have lifecycle methods for different phases of the component’s existence:Lifecycle Methods Explained
componentDidMount()
Called once after the component is rendered for the first time. Use for:
- Fetching initial data
- Setting up subscriptions
- Starting timers
useEffect(() => { ... }, [])componentDidUpdate(prevProps, prevState)
Called after every update (except the initial render). Use for:
- Responding to prop or state changes
- Fetching data based on changes
- Updating DOM
useEffect(() => { ... }, [dependencies])Error Boundaries
Error boundaries are a feature only available in class components (as of now):Using Error Boundaries
Class vs Functional Components
- Class Component
- Functional Component
Context in Class Components
Access context usingthis.context:
A class component can only consume one context. Use
Context.Consumer for multiple contexts.When to Use Class Components
Error Boundaries
Currently, error boundaries must be class components. No hook equivalent exists yet.
Legacy Code
When working with existing codebases that use class components.
Migration
Understanding classes helps when migrating old code to functional components.
Learning React
Understanding React’s evolution and core concepts.
Lifecycle Comparison
Mounting Phase
Mounting Phase
Class:
constructor() → render() → componentDidMount()Functional: Component function executes → useEffect runs after renderUpdating Phase
Updating Phase
Class:
render() → componentDidUpdate(prevProps, prevState)Functional: Component re-executes → useEffect runs if dependencies changedUnmounting Phase
Unmounting Phase
Class:
componentWillUnmount()Functional: Cleanup function returned from useEffectKey Differences
| Feature | Class Components | Functional Components |
|---|---|---|
| Syntax | ES6 classes | JavaScript functions |
| State | this.state and setState() | useState hook |
| Lifecycle | Lifecycle methods | useEffect hook |
| Context | this.context or Consumer | useContext hook |
| Performance | Slightly more overhead | Generally lighter |
| Future | Legacy approach | Recommended approach |
Source Code: Section 14 - Class-based Components