Sub topic 2
Describing UI as a function of state
This chapter assumes you know JavaScript functions, objects, arrays and ES modules, and basic HTML. You don't need to have written JSX or hooks yet. The chapters on JSX and useState cover them in detail. Here you only need the mental model that the rest of React builds on.
The core idea
React asks you to write a function that takes the current data and returns a description of what the screen should look like. In shorthand:
UI = f(state)State is the data that can change while the app runs: a counter value, the text in an input, a list of items. You never edit the page directly. You change the state, and React calls your function again to get the new description.
Imperative and declarative code
Imperative code tells the browser each step needed to get from the old screen to the new one. This vanilla JavaScript version of a like button shows the pattern:
let liked = false
const button = document.createElement('button')
button.textContent = 'Like'
document.body.appendChild(button)
button.addEventListener('click', () => {
liked = !liked
button.textContent = liked ? 'Liked' : 'Like'
button.classList.toggle('active', liked)
})Every place that changes liked must also remember to update the text and the class. With more state and more places to update, one of them gets missed and the screen disagrees with the data.
Declarative code describes the result for each state and leaves the updating to React:
import { useState } from 'react'
function LikeButton() {
const [liked, setLiked] = useState(false)
return (
<button
className={liked ? 'active' : ''}
onClick={() => setLiked(!liked)}
>
{liked ? 'Liked' : 'Like'}
</button>
)
}
export default LikeButtonThe component says what the button looks like when liked is true and when it is false. The click handler only changes the data. It never touches the button.
The render cycle
React repeats a loop of three phases:
- Render. React calls your component function with the current props and state. The function returns a description of the UI.
- Commit. React compares the new description with the previous one and applies only the differences to the browser's DOM.
- Event. The user does something. Your handler asks React to change state, which schedules a new render.
The word "render" here does not mean painting pixels. It means calling your function. Painting happens later, and only if the commit phase changed something.
State is a snapshot
Each render sees one fixed set of values. Inside a single render, count never changes, even after you call setCount. The call schedules the next render. It does not edit the variable you are holding.
import { useState } from 'react'
function TripleClick() {
const [count, setCount] = useState(0)
function addThree() {
setCount(count + 1)
setCount(count + 1)
setCount(count + 1)
}
function addThreeCorrectly() {
setCount(c => c + 1)
setCount(c => c + 1)
setCount(c => c + 1)
}
return (
<div>
<p>Count: {count}</p>
<button onClick={addThree}>+3 (buggy)</button>
<button onClick={addThreeCorrectly}>+3 (correct)</button>
</div>
)
}
export default TripleClickThe first button adds 1, because all three calls use the same count from the current render. The second button passes an updater function, c => c + 1. React queues the updaters and applies them in order, starting from the latest value, so it adds 3. Use an updater whenever the new value depends on the previous one.
Store the minimum, derive the rest
If you can compute a value from existing state or props, compute it during render instead of storing it. Two copies of the same fact can drift apart.
import { useState } from 'react'
function Cart() {
const [items, setItems] = useState([
{ id: 1, name: 'Notebook', price: 4, qty: 1 },
{ id: 2, name: 'Pen', price: 2, qty: 3 },
])
const total = items.reduce((sum, item) => sum + item.price * item.qty, 0)
function addOne(id) {
setItems(items.map(item =>
item.id === id ? { ...item, qty: item.qty + 1 } : item
))
}
return (
<section>
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} x {item.qty}
<button onClick={() => addOne(item.id)}>+1</button>
</li>
))}
</ul>
<p>Total: ${total}</p>
</section>
)
}
export default Carttotal is a plain variable. It is recalculated on every render, so it is always correct and needs no setTotal.
Rules that make the model work
React can call your component more than once, and in development StrictMode deliberately renders twice to expose problems. For that to be safe, a component's render must be pure:
- The same props and state must produce the same output.
- Rendering must not change anything that existed before it started. Local variables created during the render are fine to change.
- Side effects such as network calls, timers and direct DOM edits belong in event handlers or in effects, not in the body of the function.
You must also treat state as read-only. To change an object or array, build a new one, as addOne does with map and the spread operator. React decides whether state changed by comparing references. If you mutate the old object, the reference stays the same and React may skip the update.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Click changes data but the screen stays the same | State was mutated in place | Pass a new array or object to the setter |
| Several updates in one handler count as one | Each call reads the same snapshot | Use `setX(prev => ...)` |
| `console.log(count)` right after `setCount` shows the old value | State is a snapshot of the current render | Read the new value in the next render, or compute it in a variable first |
| Two pieces of state disagree | A derived value was stored separately | Compute it during render |
| Infinite re-render, or a "too many re-renders" error | A setter is called in the render body, or `onClick={fn()}` is used instead of `onClick={fn}` | Call setters only from handlers or effects, and pass the function itself |
Why this model pays off
You can read a component and know what it shows in every state without tracing the history of clicks. Bugs also become easier to find. If the screen is wrong, either the state is wrong or the render function is wrong, and you can check each one separately.
Exercise
A component keeps price and qty in state and also keeps total in state, updating it in both handlers. A teammate adds a third handler that changes qty and forgets to update total. What goes wrong, and how do you restructure the component so it can't happen?
Show answer
The screen shows a stale total, because the stored total no longer matches price * qty. Remove total from state and compute it in the render body with const total = price * qty. It then follows from the current state on every render, so no handler can leave it out of date.
Exercise
In a component, const [n, setN] = useState(10), a handler runs setN(n * 2); setN(n * 2);. What is n on the next render? What single change makes it 40?
Show answer
It is 20, because both calls use the same snapshot value of n (10). Change the calls to setN(prev => prev * 2) twice. The updaters run in order, so 10 becomes 20 and then 40.