React's useState()
hook is one of the fundamental hooks you'll often use when building functional components. It allows you to add state to your components, making them dynamic and interactive.
What is useState()?
The useState()
hook is a function that lets you add state variables to functional components. Before hooks, only class components could have state, but with hooks, you can now use state in functional components as well.
Syntax:
const [count, setCount] = useState(0);
How useState() Works
When you calluseState()
, it returns an array with two elements:
- The current state value.
- A function that lets you update the state.
Every time you use setState
, React triggers a re-render of the component with the updated state.
Example: Simple Counter
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>
);
}
export default Counter;
- We initialize count to 0 using useState(0).
- The setCount function is used to update the count when the button is clicked.
Example: Using Objects with useState()
import React, { useState } from 'react';
function UserProfile() {
const [user, setUser] = useState({ name: 'John Doe', age: 25 });
const updateName = () => {
setUser({ ...user, name: 'Jane Doe' });
};
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<button onClick={updateName}>Update Name</button>
</div>
);
}
export default UserProfile;
- We manage an object state representing a user profile.
- When updating the state, we use the spread operator
(...user)
to ensure we only modify the name property, keeping the age unchanged.
Top comments (2)
Please Update All the hooks with example
Yes ofcourse , we will provide all React Hooks with Examples.