Chapter 27: Reacting to Input with State
Core Idea
React's model is declarative, not imperative — instead of scripting each DOM manipulation step for every interaction ("disable this button, then show this spinner, then..."), you enumerate the possible visual states a component can be in and let React handle transitioning the UI to match whichever state is currently true.
Key Concepts
- Imperative vs. declarative: imperative UI programming means manually writing the exact sequence of DOM commands for each interaction (which gets exponentially harder to keep correct as more interaction paths are added); declarative means describing what should be shown for each state and letting the library reconcile the DOM to match.
- Process for "thinking declaratively" about a component:
- Identify the component's visual states — enumerate every distinct thing the UI can look like (e.g. for a form: empty, typing, submitting, success, error) before writing any code.
- Determine what triggers those state changes — human input (typing, clicking) or computer input (a response arriving, a timer firing).
- Represent the state in memory with
useState — as few state variables as possible; each new one adds maintenance burden.
- Remove any non-essential state variables — check for values that can be derived from other state at render time instead of stored separately (this is the same discipline covered fully in Ch 28).
- Connect the event handlers to set state — wire each interaction/response to the right state transition.
- Impossible states become simply unrepresentable when the state model is built this way — e.g.
isTyping and isSubmitting both true at once is a bug that redundant boolean flags allow; a single status enum-like variable ('empty' | 'typing' | 'submitting' | 'success' | 'error') makes that combination structurally impossible.
Code Examples
const [status, setStatus] = useState('empty'); // 'empty' | 'typing' | 'submitting' | 'success' | 'error'
- What it demonstrates: modeling mutually-exclusive visual states as one variable instead of several independent booleans — the core technique this chapter teaches.
Key Takeaways
- Enumerate visual states before writing state variables — skipping straight to
useState calls tends to produce redundant/contradictory flags.
- Prefer one state variable that can only hold one of several named values over several independent booleans meant to be mutually exclusive.
- This declarative process is the practical, step-by-step version of Ch 3's "Thinking in React" Steps 3-4, applied specifically to interaction-driven UI.
Connects To
- Ch 28 (Choosing the State Structure): the deeper rules for eliminating redundant state, referenced in step 4 here.
- Ch 3 (Thinking in React): the broader process this chapter's steps are a specialization of.