Introduction
Before React Hooks were introduced, state management was mainly handled using class components. However, React introduced Hooks in React 16.8, and one of the most commonly used Hooks is the useState Hook.
The useState Hook allows functional components to create and manage state easily without using class components.
What is useState Hook?
The useState Hook is a React Hook used to create and manage state inside functional components.
OR
useState is a Hook that adds state to functional components.
It allows components to:
- Store data
- Update data
- Re-render UI automatically
Why useState is Used?
Modern applications need dynamic and interactive behavior.
Examples:
- Counter applications
- Login forms
- Shopping carts
- Search bars
- Theme toggles
All these features require state management.
useState helps React update the UI whenever data changes.
Syntax of useState Hook
Basic syntax:
const [state, setState] = useState(initialValue);
Understanding the Syntax
state
Stores the current value.
setState
Function used to update state.
initialValue
Default value of the state.
Example of useState Hook
import { useState } from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1) } >
Increment
</button>
</div>
);
}
export default App;
Output
Whenever the button is clicked:
Component re-renders automatically
How useState Works?
- React stores state value
- Component renders UI
- User interacts with UI
- setState updates state
- React re-renders component
useState with String
State can store strings.
Example
import { useState } from "react";
function App() {
const [name, setName] = useState("Gaurav");
return (
<div>
<h1>{name}</h1>
<button onClick={() => setName("Rahul") } >
Change Name
</button>
</div>
);
}
Output
useState with Boolean
Boolean state is commonly used for toggles.
Example
import { useState } from "react";
function App() {
const [isDark, setIsDark] = useState(false);
return (
<div>
<button onClick={() => setIsDark(!isDark) } >
Toggle
</button>
<h1>
{
isDark
? "Dark Mode"
: "Light Mode"
}
</h1>
</div>
);
}
Output
useState with Arrays
State can also store arrays.
Example
import { useState } from "react";
function App() {
const [fruits, setFruits] =
useState([
"Apple",
"Mango"
]);
return (
<ul>
{
fruits.map((fruit, index) => (
<li key={index}>
{fruit}
</li>
))
}
</ul>
);
}
useState with Objects
Objects are commonly stored in state.
Example
import { useState } from "react";
function App() {
const [user, setUser] =
useState({
name: "Rahul",
age: 25
});
return (
<div>
<h1>{user.name}</h1>
<h2>{user.age}</h2>
</div>
);
}
Updating Object State
Object state should be updated carefully.
Correct Example
setUser({
...user,
age: 30
});
Why Spread Operator is Used?
The spread operator:
- Copies existing object data
- Prevents data loss
Functional Updates in useState
React allows functional updates.
Example
setCount((prevCount) =>
prevCount + 1
);
Why Functional Updates are Useful?
Useful when:
- State depends on previous value
- Multiple updates happen together
Multiple State Variables
Components can use multiple states.
Example
import { useState } from "react";
function App() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
return (
<div>
<input type="text" onChange={(e) => setName(e.target.value) } />
<input type="email" onChange={(e) => setEmail(e.target.value) } />
</div>
);
}
Real-Life Example of useState
Suppose you are building an e-commerce website.
useState manages:
- Shopping cart items
- Product quantity
- Search filters
- Login status
- Theme switching
Without useState, applications cannot become interactive.
Difference Between Normal Variable and useState
| Feature | Normal Variable | useState |
|---|---|---|
| Re-render UI | No | Yes |
| Data Persistence | No | Yes |
| React Tracking | No | Yes |
| Dynamic UI | Limited | Supported |
Advantages of useState Hook
| Feature | Benefit |
|---|---|
| Easy State Management | Simpler development |
| Functional Components | Modern React approach |
| Dynamic UI | Interactive applications |
| Automatic Re-rendering | UI updates instantly |
| Flexible Data Types | Supports all data types |
Common Mistakes in useState
1. Updating State Directly
Wrong:
count = count + 1;
Correct:
setCount(count + 1);
2. Mutating Object State
Wrong:
user.age = 30;
Correct:
setUser({
...user,
age: 30
});
3. Forgetting Initial Value
Wrong:
useState();
Always provide meaningful initial values.
4. Using State for Non-Dynamic Data
Not every variable needs state.
5. Using Too Many States
Too many separate states can make components complex.
Best Practices for useState
- Use meaningful state names
- Keep state minimal
- Use functional updates when necessary
- Avoid direct mutation
- Group related state logically
- Use multiple states carefully
Real-World Applications of useState
useState is heavily used in:
- Social media apps
- Banking apps
- E-commerce websites
- Chat applications
- Dashboards
Examples:
- Like buttons
- Notifications
- Shopping carts
- Search bars
- Form handling
useState vs Class Component State
| Feature | useState Hook | Class Component State |
|---|---|---|
| Syntax | Simple | Complex |
| Functional Components | Supported | Not Supported |
| this Keyword | Not Required | Required |
| Modern Usage | Recommended | Less Common |
useState hook – Interview Questions
Q 1: What is the useState Hook?
Q 2: How do you declare a state using useState?
Q 3: How does useState update the state?
Q 4: Can useState store objects or arrays?
Q 5: Is the state update using useState asynchronous?
useState hook – Objective Questions (MCQs)
Q1. What is the purpose of the useState hook in React?
Q2. What does the useState hook return?
Q3. Which syntax correctly declares a state variable using useState?
Q4. What happens when the state is updated using setCount?
Q5. Can useState hold objects or arrays as state?
Conclusion
The useState Hook is one of the most important features in React because it allows functional components to manage dynamic data easily. It helps developers build interactive applications with cleaner and simpler code.
useState supports:
- Strings
- Numbers
- Arrays
- Objects
- Booleans