The useState hook is one of the most commonly used hooks in React for adding state to functional components. It allows you to declare state variables in a functional component and provides a way to update those variables.
How to Use useState
1. Importing the Hook
You need to import useState from React before you can use it.
import React, { useState } from 'react';
2. Declaring State Variables
Inside your functional component, call useState with the initial state value. It returns an array with two elements:
- The current state value
- A function to update the state
function Counter() {
// Declare a state variable named `count`, initialized to 0
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
In the example above:
count
is the current state value.setCount
is the function that updates the state.useState(0)
initializescount
to0
.
3. Updating State
To update the state, call the state update function (setCount in the example) with the new state value. React will re-render the component with the updated state.
This button click updates the count state by incrementing it by 1.
4. Using State with Objects
If your state is an object, you can update it with a spread operator to maintain other properties.
function Profile() {
const [user, setUser] = useState({ name: 'John', age: 30 });
const updateName = () => {
setUser(prevUser => ({
...prevUser,
name: 'Jane'
}));
};
return (
Name: {user.name}
Age: {user.age}
);
}
5. Using State with Arrays
When dealing with arrays, you might want to add or remove items. You should use the array update functions like map, filter, or concat.
function ItemList() {
const [items, setItems] = useState(['Item 1', 'Item 2']);
const addItem = () => {
setItems([...items, `Item ${items.length + 1}`]);
};
return (
{items.map((item, index) => (
- {item}
))}
);
}
- Declare state variables.
- Update state with a setter function.
- Work with state in various formats (primitive values, objects, arrays).
- Handle complex state updates using the functional form of the state setter function.