React · module 4 of 15
State & useState
State is data that changes over time and lives inside a component. When state changes, React re-renders the component with fresh values.
What this module covers
4 steps · React
Step 1. State & useState Hook
State is data that changes over time and lives inside a component. When state changes, React re-renders the component with fresh values. import { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ); } State immutability — never mutate directly: user.name = "Bob"; // ✗ wrong setUser({ ...user, name: "Bob" }); // ✓ spread into a new object setItems([...items, newItem]); // ✓ arrays: never push/splice setItems(items.filter(i => i.id !== targetId));
Calling setCount doesn't mutate count in place — it tells React "re-render this component with this new value," which is why React can reliably detect the change. In React, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [React] Add a button that calls setCount to increment the value.
Step 2. Quiz: State & useState
Answer these questions about the useState hook.
useState returns a [value, setter] pair, and React only detects a change when a new reference is passed in — mutating the old one in place is invisible to it. In React, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [React] Answer the quiz below.
Step 3. Shopping Cart Item
Build a shopping cart item with quantity controls. Show item name, price × quantity = total, plus + and − buttons. Minimum quantity is 1.
total doesn't need its own state — deriving it from price and quantity on every render keeps it impossible to get out of sync, which is the general rule for any value computable from existing state. In React, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [React] Does the total update with quantity, and is quantity clamped to a minimum of 1?
Step 4. Mini project: State & useState
Build a shopping cart item with quantity controls. Show item name, price × quantity = total, plus + and − buttons. Minimum quantity is 1. Turn the completed challenge into a small standalone project. Add realistic content, clear naming, one edge case or error state, and a short README-style explanation of how the main idea works.
total doesn't need its own state — deriving it from price and quantity on every render keeps it impossible to get out of sync, which is the general rule for any value computable from existing state. This project stage asks you to apply the same idea without step-by-step scaffolding. In React, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [React] Does the total update with quantity, and is quantity clamped to a minimum of 1?
Loading code lab...