The useState Hook is a built-in React Hook that allows functional components to hold and manage state. Before Hooks were introduced, state could only be managed using class components. The useState Hook changed this by enabling state management in plain JavaScript functions.
The useState Hook returns an array with two elements. The first element is the current state value, and the second element is a function used to update that state. When the state update function is called, React re-renders the component with the updated state.
Basic syntax of useState:
const [state, setState] = useState(initialValue);
Here, initialValue is the value assigned to the state during the first render.
Basic Example of useState
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}
In this example, count is the state variable, and setCount updates its value. Each click updates the state and triggers a re-render.
Updating State Based on Previous Value
When updating state based on the previous state, it is recommended to use a callback function. This avoids potential bugs caused by stale state values.
Example:
setCount(prevCount => prevCount + 1);
This pattern ensures the update always uses the latest state.
Using useState with Different Data Types
The useState Hook can store different types of data such as strings, numbers, booleans, arrays, and objects.
Example with object state:
const [user, setUser] = useState({ name: "", age: 0 });
function updateName(name) {
setUser(prevUser => ({
...prevUser,
name
}));
}
This approach ensures immutability, which is critical in React state updates.
Multiple State Variables
You can use useState multiple times in a single component to manage independent pieces of state.
Example:
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
This keeps state logic clean and focused.
Real-World Scenario
In real-world applications, useState is commonly used to manage form inputs, toggle UI elements, track user actions, and handle dynamic data. For example, a login form uses useState to track email and password values, while a modal component uses it to control visibility.
Important Notes and Best Practices
Never modify state directly; always use the setter function. Keep state minimal and relevant to the component. Avoid storing derived values in state. Use functional updates when the new state depends on the previous state.
In summary, the useState Hook is the foundation of state management in modern React. Mastering useState is essential for building interactive, predictable, and scalable React applications using functional components.