State with useState

State is data that a component remembers and that can change over time: a counter, the text in an input, whether a menu is open, the items in a cart. When state changes, React re-renders the component to show the new value.

Your first state

useState(initialValue) returns a pair:

  1. count: the current value.
  2. setCount: a function to update it, which also tells React to re-render.

Functions starting with use are called hooks. They give components superpowers.

Why not a normal variable?

Click "Increment plain": the console shows the variable changing, but the screen never updates. Only state changes trigger a re-render.

Each component instance has its own state

State can hold any type

Updating objects and arrays: always make a copy

Never mutate state directly. Create a new object or array, and React will notice the change:

Instead of (mutating ✗) Do (copying ✓)
arr.push(x) [...arr, x]
arr.splice(i, 1) arr.filter((_, idx) => idx !== i)
arr[i] = x arr.map((v, idx) => (idx === i ? x : v))
obj.key = v { ...obj, key: v }

Updater functions: when the next state depends on the previous one

State updates are batched, and count stays fixed during a render. To update based on the latest value, pass a function:

Rules of hooks

  1. Only call hooks at the top level of a component: never inside loops, conditions or nested functions.
  2. Only call hooks from React components or custom hooks.

React identifies each useState by its call order, so the order must be the same on every render.

Practice: shopping cart counter

Build a product with a quantity selector: "−" and "+" buttons (minimum 0, maximum 10), the current quantity, and a total price (quantity × 499). Add an "Add to cart" button that's disabled when the quantity is 0.

✎ Check your understanding

1.What does const [value, setValue] = useState(5) give you?

2.Why use setCount(c => c + 1) instead of setCount(count + 1)?