React Class Components
Before the introduction of Hooks in 2019, React relied exclusively on JavaScript classes to handle state and lifecycle events. Understanding them is crucial for maintaining older enterprise applications.
Syntax & Setup
A class component must extend React.Component and must contain a render() method. The render method is pure and simply returns the JSX to display.
State Management
State is initialized inside the class constructor(). We must call super(props) first. Then, we set the initial state object on this.state. Crucially, we never mutate this object directly later; we rely entirely on this.setState(), which tells React to re-render the component.
The Lifecycle
Classes grant us access to "Lifecycle Hooks" (not to be confused with React Hooks). The most common are:
- componentDidMount: Runs once immediately after the component is inserted into the DOM.
- componentDidUpdate: Runs immediately after updating occurs (props or state changes).
- componentWillUnmount: Runs right before a component is removed. Used for cleanup.
View Full Legacy Context+
Class components introduced the heavy usage of the `this` keyword in JavaScript, leading to common bugs related to event handler binding. Developers either had to explicitly bind methods in the constructor `this.handleClick = this.handleClick.bind(this)` or adopt Class Properties syntax with arrow functions to lexicaly capture `this`.
