this.state: The Class Component State Object
What you'll learn: How class components stored all their state in a single this.state object, unlike the modern useState approach.
The Single State Container
In class components, all state lives in one object called this.state. This is fundamentally different from function components with hooks, where you create multiple separate state variables with useState.
Think of this.state like a single filing cabinet where all your component's data lives in one drawer, versus modern hooks which are like having multiple individual folders scattered on your desk—each dedicated to one piece of information.
The Structure
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
name: 'User',
isActive: true
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<p>Name: {this.state.name}</p>
<p>Active: {this.state.isActive ? 'Yes' : 'No'}</p>
</div>
);
}
}
Notice how count, name, and isActive all exist as properties of the same object. You access them with this.state.propertyName.
Contrast with Modern Hooks
With useState, you'd write:
const [count, setCount] = useState(0);
const [name, setName] = useState('User');
const [isActive, setIsActive] = useState(true);
Each piece of state is independent. Class components bundle everything together in this.state.
Why It Matters
This single-object approach meant you always knew where to look for state, but it also meant updating state required different techniques (which you'll learn soon). The modern hooks approach gives you more flexibility and simpler updates.
Key Takeaway: Class components store all state in one this.state object, accessed via this.state.propertyName, contrasting with hooks' multiple independent state variables.