State Updates
State is local, mutable component memory that triggers a re-render whenever updated.
Mental Model
"The Scoreboard: When a team scores, you update the digital display (setter), and the stadium scoreboard flashes the new number immediately."
Interactive Engine Simulation
Component remembers '0'
State is like a component's personal notebook. When the information in that notebook changes, React automatically knows it needs to update the UI.
Executable Code Snippet
1function Counter() {
2 // 1. Declare state
3 const [count, setCount] = useState(0);
4
5 return (
6 <div>
7 <p>Count: {count}</p>
8 {/* 2. Update state to trigger render */}
9 <button onClick={() => setCount(count + 1)}>
10 Increment
11 </button>
12 </div>
13 );
14}- 01.Component re-renders are triggered by state or prop changes.
- 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
- 03.Automatic batching optimizes multiple state updates into a single render cycle.
01. Local Memory
State is a component's personal memory. Unlike regular variables, which are erased when a function finishes executing, **State persists** across re-renders. When state changes, React "schedules" a re-render to update the visual manifestation.
State vs Variable
// Lost on re-render
// Persistent memory
02. Asynchronous Snapshots
Calling `setState` does not change the variable immediately. Instead, it tells React to create a new "snapshot" of the UI with the new value. Within the current execution frame, the state variable remains unchanged. This is why **Functional Updates** (`setCount(c => c + 1)`) are essential for sequence safety.
Senior Insight
"React state is like a **Git Commit**. When you call the setter, you are proposing a new version of the reality. React reviews the proposal and merges it into the main branch (the real DOM) during the commit phase."