🪝 Introduction to useState
The useState Hook is one of the most commonly used React Hooks. It allows a functional component to store and update state. Whenever the state changes, React automatically re-renders the component so the user interface reflects the latest data.
Important
🎯 Why Use useState?
Before Hooks, only class components could manage state. The introduction of useState made it possible for functional components to store and update state without using classes.
- Store values that change over time.
- Automatically update the UI when state changes.
- Keep components simple and readable.
- Eliminate the need for class components in many cases.
⚙️ Syntax
Basic Syntax
const [state, setState] = useState(initialValue);| Part | Description |
|---|---|
| state | The current value stored by React. |
| setState | A function used to update the state. |
| initialValue | The value assigned during the first render. |
🔄 How useState Works
💻 Example 1: Counter
Counter Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</>
);
}Initially, count is 0. Clicking the button calls setCount(), which updates the value and causes React to render the component again with the new count.
📝 Example 2: Managing Text Input
Input Example
import { useState } from "react";
function NameInput() {
const [name, setName] = useState("");
return (
<>
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Hello, {name}</p>
</>
);
}The input field is controlled by the name state. Every keystroke updates the state, and the greeting changes immediately.
🎨 Example 3: Toggle Button
Boolean State
import { useState } from "react";
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
<button onClick={() => setIsOn(!isOn)}>
{isOn ? "ON" : "OFF"}
</button>
);
}Boolean values are commonly used with useState to control visibility, switches, and toggle buttons.
📊 Types of State Values
| Data Type | Example Initial Value | Typical Use |
|---|---|---|
| Number | 0 | Counters, scores |
| String | "" | User input, names |
| Boolean | false | Toggles, modals |
| Array | [] | Lists of items |
| Object | User profiles, settings |
🧠 Updating State Correctly
Updating Primitive Values
Updating a Number
setCount(count + 1);Updating Objects
Updating an Object
setUser({
...user,
age: 26
});Updating Arrays
Updating an Array
setItems([
...items,
"New Item"
]);Warning
⚡ Functional State Updates
When the next state depends on the previous state, pass a function to setState(). This ensures React uses the latest available state value.
Functional Update
setCount(previousCount => previousCount + 1);Best Practice
📋 Common Use Cases
Store form fields such as names, email addresses, and passwords using useState.
Maintain scores, likes, quantities, and other numeric values.
Show or hide dialogs, menus, and sections using boolean state.
Manage collections of data such as shopping carts, todo lists, and notifications.
🚫 Common Mistakes
- Updating state directly instead of using the setter function.
- Mutating arrays or objects instead of creating new ones.
- Expecting state updates to happen immediately after calling the setter.
- Using too many separate state variables when related values could be grouped.
✅ Best Practices
- Choose meaningful names for state variables.
- Keep state as small as possible.
- Use functional updates when relying on previous state.
- Store only data that changes over time.
- Never mutate state directly.
📚 Official Resource
Learn more about useState in the official React documentation at React useState Documentation.