What is state?
State is data that can change over time - a form input, a toggle button, items in a shopping cart. When state changes, React automatically updates the UI to match. TheuseState hook is how you add state to function components. You’ll use it constantly.
Basic useState example
Counter.jsx
useState(0) returns an array with two items:
- The current value (
count) - A function to update it (
setCount)
const [count, setCount] = useState(0).
How state updates work
setCount(5), React schedules a re-render but doesn’t update count immediately inside the current event handler. The new value will be available on the next render.
Updating state based on previous value
setCount(prev => prev + 1). This ensures you always get the latest value, even if multiple updates happen.
State with objects
UserProfile.jsx
... to create a new object with the updated property. React only detects changes when you pass a new object to the setter.
Multiple state variables
UserForm.jsx
useState calls as you need. Each one is independent. Here we track form inputs, loading state, and errors separately.
The
disabled={isSubmitting} prevents users from submitting the form multiple times while a request is in flight. This is a crucial UX pattern.State with arrays
TodoList.jsx
- Add item:
[...array, newItem] - Update item:
array.map(item => item.id === id ? updatedItem : item) - Remove item:
array.filter(item => item.id !== id)
When to split state vs keep together
Common mistakes
Mutating state directly
Mutating state directly
Using stale state in updates
Using stale state in updates
Forgetting that state updates are asynchronous
Forgetting that state updates are asynchronous
Not using keys in lists
Not using keys in lists
What’s next?
State lets you manage data within a component. Now let’s learn how to fetch data from your backend when a component first loads.Side effects with useEffect
Fetch data when your component mounts