HomeReact
Chapter 3

03 — State & Events

State is data that changes over time and triggers re-renders. Events let you respond to user interactions. Together they make React apps interactive.

State Fundamentals

  • useState returns [value, setter] — call the setter to update and re-render
  • State is per component instance — each <Counter /> has its own state
  • State updates are asynchronous — React batches multiple updates for performance
  • State is immutable — always create new values (don't mutate)
  • When state changes, the component re-renders (function runs again)

useState Rules

const [count, setCount] = useState(0);           // initial value
const [name, setName] = useState("");             // string
const [items, setItems] = useState<string[]>([]); // typed array
RuleExample
Direct valuesetCount(5)
Updater functionsetCount(prev => prev + 1) — use when new value depends on old
New object/arraysetItems([...items, newItem]) — never mutate

Events in React

HTMLReact
onclickonClick
onchangeonChange
onsubmitonSubmit
onkeydownonKeyDown
onfocusonFocus
  • Event handlers receive a SyntheticEvent (React's cross-browser wrapper)
  • Pass a function reference, not a function call: onClick={handleClick} not onClick={handleClick()}

Lifting State Up

When two sibling components need to share state:

  1. Move the state to their closest common parent
  2. Pass state down as props
  3. Pass setter/callback down for children to update

File

  • state-events.tsx — useState, updater functions, event handling, typing events, lifting state, state batching