π useState() Hook in React
The useState
hook allows you to add state to functional components. It's one of the most used hooks in React.
β Basic Example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click Me
</button>
</div>
);
}
- useState(0)
initializes the count at 0.
- setCount
updates the state and triggers a re-render.
π¦ Using Multiple States
function Profile() {
const [name, setName] = useState('');
const [age, setAge] = useState(18);
return (
<div>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<input
type="number"
value={age}
onChange={(e) => setAge(e.target.value)}
/>
<p>{name} is {age} years old.</p>
</div>
);
}
π§ Updating Objects in State
const [formData, setFormData] = useState({ username: "", email: "" });
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
When working with objects, use the spread operator to preserve existing state while updating one property.
π‘ Tips
- Each call to
useState
gives one piece of state. - You can use any type: number, string, array, object, etc.
- State updates are asynchronous.
- Donβt mutate state directly (e.g. donβt do
state.count++
).