The useState
hook is a fundamental part of React that allows you to add state to functional components. Here's a detailed look at how it works:
What is useState
?
useState
is a hook that lets you add state variables to your functional components. It returns an array with two elements:
- The current state value.
- A function to update that state.
Basic Usage
To use useState
, you need to import it from React and call it inside your functional component:
import React, { useState } from 'react';
function Counter() {
// Declare a state variable named 'count', initialized to 0
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;
How It Works
-
Initial State: The argument passed to
useState
(in this case,0
) is the initial state. -
State Variable: The first element of the array (
count
) is the current state. -
State Setter Function: The second element (
setCount
) is a function that updates the state.
Updating State
You should always use the state setter function to update the state. Directly modifying the state variable won't trigger a re-render:
<button onClick={() => setCount(count + 1)}>Click me</button>
Multiple State Variables
You can use multiple useState
calls to manage different pieces of state:
function UserProfile() {
const [name, setName] = useState('John Doe');
const [age, setAge] = useState(30);
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<button onClick={() => setAge(age + 1)}>Increase Age</button>
</div>
);
}
Complex State
For more complex state, you can use objects or arrays:
function Car() {
const [car, setCar] = useState({ brand: 'Ford', model: 'Mustang', year: 1964 });
const updateCar = () => {
setCar(prevCar => ({
...prevCar,
color: 'blue'
}));
};
return (
<div>
<h1>My {car.brand}</h1>
<p>It is a {car.color} {car.model} from {car.year}.</p>
<button onClick={updateCar}>Change Color</button>
</div>
);
}
Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.
If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!
Thanks again for stopping by! 😊
Top comments (0)