Understanding `useState` in React
Source: Dev.to
What Problem Does useState Solve?
Before React, updating something on the screen required:
- Finding the HTML element
- Manually updating it
- Making sure nothing else broke
React changes this completely. It 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.
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, useState is how React remembers values.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
{count}
setCount(count + 1)}>+
</>
);
}
What the line const [count, setCount] = useState(0); does
- 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.
How It Differs from Direct Mutation
❌ This will NOT work correctly:
count = count + 1; // Direct mutation
✅ This is correct:
setCount(count + 1); // Use the setter
Why?
React tracks state changes through the setter function. Direct mutation bypasses React, so no re‑render happens.
When to Use useState
Use useState when:
- Data changes based on user interaction
- The UI should update when that data changes
Typical examples:
- Form inputs
- Toggle switches
- Counters
- Loading states
- Modal open/close
useState lets your component remember data and react to changes. Master this first—everything else builds on it.