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
useStatereturns[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| Rule | Example |
|---|---|
| Direct value | setCount(5) |
| Updater function | setCount(prev => prev + 1) — use when new value depends on old |
| New object/array | setItems([...items, newItem]) — never mutate |
Events in React
| HTML | React |
|---|---|
onclick | onClick |
onchange | onChange |
onsubmit | onSubmit |
onkeydown | onKeyDown |
onfocus | onFocus |
- Event handlers receive a SyntheticEvent (React's cross-browser wrapper)
- Pass a function reference, not a function call:
onClick={handleClick}notonClick={handleClick()}
Lifting State Up
When two sibling components need to share state:
- Move the state to their closest common parent
- Pass state down as props
- Pass setter/callback down for children to update
File
state-events.tsx— useState, updater functions, event handling, typing events, lifting state, state batching