What Problem Does useState Solve?
Before React, changing something on the screen meant:
- Finding the HTML element
- Manually updating it
- Making sure nothing else breaks
React changes this completely.
React says:
“Tell me what the UI should look like for a given state, and I’ll handle updates.”
To do that, React needs a way to store changing data.
That’s where useState comes in.
What Is useState?
useState is a React Hook that lets a component:
- Store data
- Update that data
- Automatically re-render the UI when the data changes
In simple terms:
useStateis how React remembers values.
Basic Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<p>{count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</>
);
}
Breaking It Down Slowly
const [count, setCount] = useState(0);
This line does three things:
- Creates a state variable →
count - Creates a function to update it →
setCount - Sets the initial value →
0
Think of it like backend code:
let count = 0;
function setCount(newValue) {
count = newValue;
}
Except React also updates the UI automatically.
Why You Must Use the Setter Function
❌ This will NOT work correctly:
count = count + 1;
✅ This is correct:
setCount(count + 1);
Why?
- React tracks state changes through the setter
- Direct mutation bypasses React
- No re-render happens
When to Use useState
Use useState when:
- Data changes based on user interaction
- UI should update when data changes
Examples:
- Form inputs
- Toggle switches
- Counters
- Loading states
- Modal open/close
Key Takeaway
useStatelets your component remember data and react to changes.
Master this first. Everything else depends on it.
Top comments (1)
Really clear and beginner friendly article — thank you!