If you want to manage state in functional components, then useState in React is your best friend.
What is useState?
useState
is a React Hook used to manage state in functional components.
In class components, you need to use this.state
and this.setState
, but in functional components, you can directly use useState
.
Basic Syntax of useState
Before using useState
, you need to import it from React:
import { useState } from "react";
Syntax:
const [state, setState] = useState(initialValue);
Here,
state
: Stores the current state value.setState
: Function for updating the state.initialValue
: Sets the initial or default value of the state.
useState
uses array destructuring, where the first value is the state and the second is a function that updates the state.
For example:
const [count, setCount] = useState(0);
In this example,
count
: Stores the current count value.setCount
: Function for updating the count.0
: Sets the initial or default value of the count to 0.
Example of useState (Counter App)
Let’s understand useState with a simple counter app example.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
export default Counter;
In this example,
- The initial value is set to 0.
- The count state is updated by using the setCount.
- On each button click, the state (count) is updated, and the component is re-rendered.
useState with Different Data Types
With useState
, you can store not just numbers but also strings, booleans, and arrays.
useState with String
function UserComponent() {
const [name, setName] = useState("John");
return (
<div>
<h1>My Name is: {name}</h1>
<button onClick={() => setName("David")}>
Change Name
</button>
</div>
);
}
Here, the initial value is “John”, and on button click, this will change to”David”.
useState with Boolean
function ToggleComponent() {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
{isVisible && <h1>Hello World!</h1>}
<button onClick={() => setIsVisible(!isVisible)}>
Toggle Visibility
</button>
</div>
);
}
In this example,
!isVisible
is used to toggle the boolean.- On button click, true and false will be toggled (true → false or false → true).
useState with Array
function ListComponent() {
const [items, setItems] = useState(["Apple", "Banana", "Mango"]);
return (
<div>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<button onClick={() => setItems([...items, "Orange"])}>
Add Item
</button>
</div>
);
}
In this example,
- To manage the state or the array, it’s a best practice to use the spread operator
[…]
. setItems([…items, “Orange”])
will add “Orange” while retaining the old items.
Best Practices for Updating State
Keep these practices in mind for updating the state:
Functional Updates (Using Previous State)
If the new state depends on the previous state, use a callback function.
The reason for this:
- React is asynchronous, and direct state updates can be slow.
- Functional state ensures that you work on the latest state.
For example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(prevCount => prevCount + 1)}>
Increment
</button>
);
}
export default Counter;
Managing Multiple State Variables
You can manage multiple states inside one component.
For example:
import { useState } from "react";
function UserInfo() {
const [name, setName] = useState("John");
const [age, setAge] = useState(25);
return (
<div>
<h1>Name: {name}</h1>
<h2>Age: {age}</h2>
<button onClick={() => setAge(age + 1)}>Increase Age</button>
</div>
);
}
Handling State Updates in Objects
If you are managing an object or array, then the state gets replaced, not merged.
For example:
const [user, setUser] = useState({ name: "John", age: 25 });
setUser({ age: 26 }); // This will replace the "name" field
To fix this issue, use the spread operator:
setUser(prevUser => ({ ...prevUser, age: 26 }));
This will update the age while retaining the old values.
When to Use useState?
- When you want to store small or medium state values.
- When re-rendering of component is needed after state change.
- When local state (not shared globally) is required.
- When you want to handle form inputs or user interactions.
For complex states, consider useReducer
instead of useState
.