What is useState in React?
In React, useState is a powerful Hook that allows you to add state to your functional components. State is used to store data that may change over time and is essential for creating interactive components. Before React Hooks were introduced, state management was only possible in class-based components. With useState, functional components can now handle state easily.
Why use useState?
- Dynamic Behavior: It allows components to update and re-render dynamically when data changes.
- Simpler Code: Using useState makes state management more straightforward compared to class components.
- Improved Readability: It enhances the readability and maintainability of functional components.
How to Use useState
The useState Hook is imported from React and used within a functional component. It follows this syntax:
const [state, setState] = useState(initialValue);
Parameters:
- state: This is the current value of the state.
- setState: A function used to update the state value.
- initialValue: The initial value of the state (can be a number, string, array, object or null).
Returns:
The useState Hook returns an array with two elements:
- The current state value.
- A function to update that state value.
Example: Counter Using useState
Here’s a simple example of a counter application:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state with 0
const increment = () => {
setCount(count + 1); // Update state
};
const decrement = () => {
setCount(count - 1); // Update state
};
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default Counter;
Explanation:
- Initial State:
count
starts with 0 because of useState(0). - Update State: Clicking the “Increment” button calls setCount(count + 1), which updates the count value and re-renders the component.
- Dynamic Behavior: The count value changes dynamically on the UI without manually refreshing the page.
Key Points to Remember About useState
Multiple States: You can use multiple useState Hooks in a single component for managing different pieces of state:
const [name, setName] = useState('');
const [age, setAge] = useState(0);
State Updates Are Asynchronous: React batches multiple state updates for better performance. If you need the updated state immediately, use a callback function:
setCount(prevCount => prevCount + 1);
Complex State: You can use useState to manage objects or arrays. However, when updating complex state, remember to preserve the existing state using the spread operator:
const [user, setUser] = useState({ name: '', age: 0 });
const updateName = () => {
setUser({ ...user, name: 'John' }); // Preserve other properties
};
Avoid Direct State Mutation: Do not directly modify the state (e.g., state = value). Always use the setState function.
Real-World Example: Form Handling
Here’s how useState can be used to handle a simple form:
import React, { useState } from 'react';
function SignupForm() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Email: ${email}, Password: ${password}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<br />
<label>
Password:
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
export default SignupForm;
Benefits of useState in React
- Simple and Intuitive: Easy to learn and use.
- Component-Based State Management: Keeps the state localized within the component.
- Lightweight: No need for external libraries for basic state management.
- Reusability: Can be used in any functional component without complex configurations.