React useState Hook — Complete Guide with Examples
Learn how to use useState in React to manage component state. Covers basic usage, functional updates, lazy initialization, and common patterns for beginners and advanced developers.
Detailed Explanation
Understanding useState
useState is the most fundamental React hook. It lets you add state to function components, replacing the need for class component this.state and this.setState.
Basic Syntax
const [state, setState] = useState(initialValue);
The hook returns a tuple: the current state value and a setter function. React preserves state between re-renders by tracking the order of hook calls within each component.
Functional Updates
When new state depends on the previous state, use the functional form of setState:
setCount(prevCount => prevCount + 1);
This avoids stale closure bugs and ensures you always work with the latest value, especially important in event handlers and effects that reference state.
Lazy Initialization
If computing the initial state is expensive, pass a function instead of a value:
const [data, setData] = useState(() => {
return JSON.parse(localStorage.getItem("data") || "{}");
});
The function runs only during the first render, avoiding unnecessary computation on subsequent renders.
Objects and Arrays
Unlike class component setState, useState's setter does not merge objects. You must spread manually:
const [user, setUser] = useState({ name: "", age: 0 });
setUser(prev => ({ ...prev, name: "Alice" }));
When to Use Multiple useState Calls
Split state into multiple useState calls when pieces of state are logically independent. If they always change together, consider combining them into a single object or using useReducer.
Use Case
Use useState for simple, independent pieces of state like form inputs, toggle flags, counters, and selected items. It is the starting point for any stateful logic in a React function component.
Try It — React Hooks Reference
Related Topics
React useReducer for Complex State — Forms, State Machines, and Redux Patterns
State Hooks
React useEffect for Data Fetching — Patterns and Best Practices
Effect Hooks
React useRef — DOM Access, Mutable Values, and Previous State
Ref Hooks
React useContext for Theming — Dark Mode and Theme Switching
Context Hooks