Sub topic 2
Describing UI as a function of state
This chapter assumes you know JavaScript functions, arrays, and the spread operator. It also assumes you have seen the basic shape of a React component. You don't need Vite yet.
The working model
React asks you to treat the screen as the output of a function. The input is your data, called state. The output is a description of the UI for that data.
UI = f(state)With direct DOM code, you write the steps that move the page from one condition to the next. You find the list element, append a node, update a counter, and hide an empty-state message. Each new feature adds more steps, and the page can drift out of sync with your data.
With React, you describe the finished result for any state. When state changes, React calls your function again and compares the new description with the previous one. It then updates only the parts of the DOM that differ. This style is called declarative.
A worked example
import { useState } from 'react'
function Inbox() {
const [messages, setMessages] = useState(['Welcome'])
return (
<section>
<h2>Inbox ({messages.length})</h2>
{messages.length === 0 ? (
<p>No messages</p>
) : (
<ul>
{messages.map((m) => (
<li key={m}>{m}</li>
))}
</ul>
)}
<button
onClick={() =>
setMessages([...messages, `Message ${messages.length + 1}`])
}
>
Add
</button>
<button onClick={() => setMessages([])}>Clear</button>
</section>
)
}
export default InboxNo code here hides or shows the empty message. The conditional expression describes both cases, and the current value of messages selects one. The handlers only change state.
The render cycle
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `messages.push('Hi')` | The array changes but React sees the same reference, so nothing re-renders. | Pass a new array: `setMessages([...messages, 'Hi'])`. |
| Reading state right after calling the setter | You still see the old value, because the new value arrives on the next render. | Compute the new value in a variable and use that. |
| Changing the DOM by hand | React's next render can overwrite your change. | Put the data in state and render from it. |
Keep render functions pure. For the same state and props, a component should return the same output and should not change anything outside itself.
Exercise
In the Inbox example, you add a "Mark all read" feature that shows "All read" instead of the list. What should you add: code that hides the <ul> element, or new state? Explain.
Show answer
Add new state, such as const [allRead, setAllRead] = useState(false). Render "All read" or the list from that value, and have the button call setAllRead(true). The component then describes the UI for each state value, and React updates the DOM.