The useState
hook in React is a powerful feature that allows you to add state to functional components. It lets you manage state variables within your function components without needing to convert them into class components.
Basic Usage
The useState
hook returns an array containing the current state and a function to update that state.
import React, { useState } from 'react';
export default function Counter() {
// Declare a state variable named "count" and a function "setCount" to update it
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Initial State
The argument passed to useState
is the initial state value. It can be any type, including objects, arrays, or even other hooks.
import React, { useState } from 'react';
export default function UserProfile() {
const [user, setUser] = useState({ name: 'John', age: 30 });
const updateName = () => {
setUser({ ...user, name: 'Jane' });
};
return (
<div>
<p>Name: {user.name}</p>
<p>Age: {user.age}</p>
<button onClick={updateName}>Change Name</button>
</div>
);
}
Updating State
The state updating function (setState
) can take the new state value directly or a function that receives the current state and returns the new state.
import React, { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
Functional State Update
Using a function to update state is useful when the new state depends on the previous state.
import React, { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(prevCount => prevCount + 1)}>Click me</button>
</div>
);
}
Using Multiple State Variables
You can use multiple useState
hooks to manage different state variables.
import React, { useState } from 'react';
export default function MultiStateComponent() {
const [name, setName] = useState('John');
const [age, setAge] = useState(30);
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<button onClick={() => setName('Jane')}>Change Name</button>
<button onClick={() => setAge(35)}>Change Age</button>
</div>
);
}