The useState hook allows functional React components to hold and update local reactive state. When state changes, React automatically re-renders the component to reflect the new state in the Virtual DOM.
const [state, setState] = useState(initialValue);
state: Current state value during render.setState: Setter function used to update the state variable.initialValue: Initial value (primitive, object, array, or lazy initializer function).flowchart LR
Init["useState(0)"] --> Render["Component Renders (count = 0)"]
User["User clicks +1"] --> Setter["setCount(prev => prev + 1)"]
Setter --> ReRender["React Re-renders Component (count = 1)"]
import React, { useState } from 'react';
export default function StateDemo() {
// 1. Primitive State
const [count, setCount] = useState(0);
// 2. Object State
const [user, setUser] = useState({ name: 'Alice', age: 28 });
// 3. Lazy Initial State Computation (Expensive computation runs only on initial mount)
const [data] = useState(() => {
const saved = localStorage.getItem('app_config');
return saved ? JSON.parse(saved) : { theme: 'dark' };
});
// Functional State Updater (Safe for asynchronous/batched updates)
const handleIncrement = () => {
setCount((prevCount) => prevCount + 1);
};
// Object Property Immutable Update Pattern
const handleAgeIncrease = () => {
setUser((prevUser) => ({
...prevUser,
age: prevUser.age + 1,
}));
};
return (
<div className="card">
<h3>Counter: {count}</h3>
<button onClick={handleIncrement}>Increment Count</button>
<h3>User: {user.name} ({user.age} yrs)</h3>
<button onClick={handleAgeIncrease}>Celebrate Birthday</button>
</div>
);
}
setCount(count + 1) called twice in the same handler will only increment by 1 due to stale closures. Use setCount(prev => prev + 1) for reliable state calculations.user.age = 29 fails to trigger a component re-render. Always supply a new object copy: setUser({ ...user, age: 29 }).Build a toggle component using useState that switches a button label between "ON" and "OFF".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With