From constructor State to useState
You'll learn how to convert the old class-based state initialization pattern into the modern useState hook syntax.
The Old Way: Constructor State
In class components, you initialized state inside the constructor method by assigning an object to this.state:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
message: 'Hello'
};
}
render() {
return <div>{this.state.count}</div>;
}
}
You bundled all your state into one big object, then accessed pieces with this.state.propertyName.
The New Way: useState Hook
With hooks, each piece of state gets its own useState call. The initial value goes inside the parentheses:
function Counter() {
const [count, setCount] = useState(0);
const [message, setMessage] = useState('Hello');
return <div>{count}</div>;
}
Think of it like this: Instead of packing all your clothes into one suitcase (the state object), you now have separate drawers for shirts, pants, and socks (individual state variables). Each drawer has its own label and knows only about its contents.
Key Differences
- No constructor needed —
useStateruns during the function component's execution - Multiple calls — Each state value gets its own
useStateline - Direct access — Use
countinstead ofthis.state.count - Initial value — The argument to
useState(initialValue)replaces what you assigned in the constructor
Key Takeaway: Converting class state to hooks means replacing one this.state = {...} assignment in the constructor with multiple useState(initialValue) calls, one per state variable.