React useState Hook – How React Updates the UI
When I started learning React, I had a small doubt. Why doesn't React update the UI when I change a normal JavaScript variable? In JavaScript, we can easily change a variable: let count = 0; count++; console.log(co
When I started learning React, I had a small doubt.
Why doesn't React update the UI when I change a normal JavaScript variable?
In JavaScript, we can easily change a variable:
let count = 0;
count++;
console.log(count); // 1
But in React, changing a normal variable doesn't update the screen.
So, how do we update the UI?
That's where useState comes in.
What is useState?
useState is a React Hook that allows us to store data and update the UI when that data changes.
Let's see a simple example.
My first example: Counter
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
export default Counter;
Here:
-
useState(0)sets the initial value to 0. -
countholds the current value. -
setCountupdates the state.
When we click the button, setCount requests a state update.
React renders the component again and displays the updated value.
Simple, right?
Why not use a normal variable?
Let's try this:
function Counter() {
let count = 0;
return (
<div>
<h1>{count}</h1>
<button onClick={() => count++}>
Increment
</button>
</div>
);
}
The value changes in JavaScript, but the UI doesn't update.
Why?
Because React doesn't know that the normal variable has changed.
That's why we use useState.
Can we store different values?
Yes! We can use useState with different data types.
const [name, setName] = useState("Raja");
const [age, setAge] = useState(21);
const [isLogin, setIsLogin] = useState(false);
const [skills, setSkills] = useState(["Java", "React"]);
const [user, setUser] = useState({
name: "Raja",
age: 21
});
We can use it for forms, todo lists, login pages, and many other applications.
One more thing: Previous state
We can update state using its previous value.
setCount(prev => prev + 1);
Here, prev represents the previous state value.
This is useful when our next state depends on the previous state.
What I learned
After practising useState, I understood three important things:
- Normal variables don't trigger React renders.
-
useStatehelps React remember values between renders. - Updating state causes React to render the component again.
Initially, I thought useState was just another way to declare variables.
But now I understand why it's important in React.
Learning React is easier when we understand why something is used instead of just memorizing its syntax.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.