← React.js learning path
React.js · Module 4 of 10

State with useState

State is data a component owns; changing it re-renders the component.

📖 Key ideas

  1. const [count, setCount] = useState(0); creates state.
  2. Calling setCount(newValue) updates state and re-renders.
  3. Never change state directly (count++ does not re-render).
  4. Use the updater form when based on old value: setCount(c => c + 1).
  5. Copy objects and arrays when updating: setUser({ ...user, age: 21 }).
💡 Real-life example: State is a scoreboard: when the score changes, the board updates for everyone to see.
useStateHook that adds state
SetterFunction that updates state
Re-renderReact redraws the component
Updater functionsetX(prev => ...)