What useState Does: Adding State to Function Components
What you'll learn: How the useState Hook allows function components to remember and update values across re-renders.
The Problem Before useState
Remember that in React, every time a component re-renders, the function runs again from top to bottom. This means regular variables get reset to their initial values:
function Counter() {
let count = 0; // This resets to 0 every single render!
// No way to "remember" the previous value
return <div>{count}</div>;
}
What useState Solves
useState is a special React function (a "Hook") that gives function components memory. It lets you declare a piece of state—a value that React remembers between renders, even though your function runs fresh each time.
Think of it like React keeping a notebook behind the scenes. When you call useState, you're asking React: "Please remember this value for me, and when I need to change it, re-run my component with the new value."
The Core Capability
With useState, you can:
- Declare a state variable that persists between renders
- Read that variable's current value
- Update that variable, which triggers a re-render with the new value
This transforms function components from simple, stateless presentation functions into fully capable components that can manage their own data and respond to user interactions over time.
Key Takeaway: useState gives function components the ability to remember values between renders—turning them from stateless helpers into stateful, interactive UI pieces that can change over time.