React components are just functions. Without `useState`, variables would reset every time the function runs. State gives your component a memory.
It returns an array with two items: the current state value, and a function to update it.
import { useState } from 'react';
function Counter() {
// 1. Declare state variable "count"
// 2. Initialize it to 0
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}If your new state depends on the old state, always use the functional form. This ensures you're working with the latest value, especially during batching.
// ❌ Potentially Buggy (uses stale 'count')
setCount(count + 1);
setCount(count + 1); // might not increment twice!
// ✅ Safe & Reliable (uses 'prev')
setCount(prev => prev + 1);
setCount(prev => prev + 1); // Guaranteed to increment twiceNever mutate state directly. Always create a new object and copy the old properties first.
const [user, setUser] = useState({ name: 'Alice', age: 25 });
// ❌ BAD: Mutating state directly
user.age = 26; // React won't know!
// ❌ BAD: Overwriting the object
setUser({ age: 26 }); // Lost the name!
// ✅ GOOD: Spreading properties
setUser(prev => ({
...prev, // Copy name: 'Alice'
age: 26 // Overwrite age
}));Now that your component has memory, let's learn how to make it *do things* (side effects) like fetching data.
Learn useEffect