Sub topic 6
Remembering values with useState
This chapter covers how a component keeps a value between renders with useState, and the mistakes that most often go wrong with it. It assumes you know JavaScript functions, objects, arrays and ES modules. It also assumes you have read the earlier chapters on components, JSX and props.
Why a plain variable is not enough
A component is a function. React calls it every time it needs to know what the component should show. Each call starts fresh, so a local variable is created again with its initial value.
function BrokenCounter() {
let count = 0
return (
<button onClick={() => { count = count + 1 }}>
Clicks: {count}
</button>
)
}
export default BrokenCounterThis component has two problems. Changing count does not tell React to render again, so the screen stays at 0. Even if a render did happen, the function would run again and reset count to 0.
State fixes both problems. State is a value that React stores for a component outside the function call. Changing it also schedules a new render.
The useState hook
useState is a hook, a function that lets a component use a React feature. You call it with the initial value. It returns an array with two items: the current value and a function that sets a new value.
import { useState } from 'react'
function Counter({ label }) {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
)
}
export default CounterThe line const [count, setCount] = useState(0) uses array destructuring. The names are yours to choose. The convention is thing and setThing.
The sequence when you click the button is:
- The click handler calls
setCount(count + 1). - React stores the new value and schedules a render of
Counter. - React calls
Counteragain. This timeuseState(0)returns the stored value, not 0. The initial value is used only on the first render. - React compares the new JSX with the previous output and updates only the parts of the page that changed.
Props and state compared
Props and state both affect what a component renders, but they have different owners.
| Row | Props | State |
|---|---|---|
| Who sets it | The parent component | The component itself |
| Can the component change it | No, treat it as read-only | Yes, through the setter |
| Typical use | Configuration such as `label` | Values that change over time, such as `count` |
In the Counter example, label is a prop and count is state. Two Counter components in the same parent each keep their own count.
Rules for hooks
React identifies each useState call by the order in which it happens during a render. Because of that, two rules apply:
- Call hooks only at the top level of a component. Do not call them inside
ifstatements, loops or nested functions. - Call hooks only from function components or from your own custom hooks. Custom hook names start with
use.
import { useState } from 'react'
// Wrong: the number of hook calls can change between renders
function Bad({ show }) {
if (show) {
const [value, setValue] = useState('')
}
return null
}React's lint rules and the Vite React template's ESLint setup flag this pattern.
State is a snapshot
The most common source of confusion is that state does not change inside the render that is already running. Each render sees one fixed value of count. Calling the setter asks for the next render.
import { useState } from 'react'
function TripleClick() {
const [count, setCount] = useState(0)
function handleClick() {
setCount(count + 1)
setCount(count + 1)
setCount(count + 1)
console.log(count) // still the value from this render
}
return <button onClick={handleClick}>Count: {count}</button>
}
export default TripleClickIf count is 0, all three calls become setCount(0 + 1). The result after the click is 1, not 3. The console.log also prints 0.
Functional updates
When the next value depends on the previous one, pass a function to the setter. React calls it with the latest pending value.
function handleClick() {
setCount(prev => prev + 1)
setCount(prev => prev + 1)
setCount(prev => prev + 1)
}Now the result is 3. React queues the three updaters and applies them in order. React also batches the updates, so this handler causes one render, not three.
Use the functional form whenever the new value is computed from the old one, especially in timers and asynchronous callbacks where the captured count may be out of date.
Updating objects and arrays
React decides whether state changed by comparing the old and new values with Object.is. If you mutate an object or array in place and pass the same reference to the setter, React sees no change and may skip the render. Always create a new object or array.
import { useState } from 'react'
function TodoList() {
const [todos, setTodos] = useState(['Install Node.js'])
const [draft, setDraft] = useState('')
function addTodo() {
if (draft.trim() === '') return
setTodos([...todos, draft])
setDraft('')
}
return (
<section>
<input
value={draft}
onChange={e => setDraft(e.target.value)}
/>
<button onClick={addTodo}>Add</button>
<ul>
{todos.map((todo, index) => (
<li key={index}>{todo}</li>
))}
</ul>
</section>
)
}
export default TodoListHere [...todos, draft] builds a new array. Calling todos.push(draft) would mutate the existing one and is the usual mistake. For objects, copy with spread in the same way:
setUser({ ...user, name: 'Ada' })Spread copies only one level. For nested objects, copy each level you change.
The key here uses the array index only because this list never reorders or removes items. For lists that do, use a stable id.
This example also shows a controlled input. The value comes from state and onChange writes back to it, so React is the single source of truth for what the field contains.
Lazy initial state
The argument to useState is used only on the first render, but JavaScript still evaluates the expression on every render. For expensive work, pass a function. React calls it once.
import { useState } from 'react'
function Notes() {
const [text, setText] = useState(() => {
return localStorage.getItem('notes') ?? ''
})
return (
<textarea value={text} onChange={e => setText(e.target.value)} />
)
}
export default NotesWrite useState(() => readFromStorage()), not useState(readFromStorage()). The second form runs readFromStorage on every render and discards the result after the first.
Common errors
- Mutating state.
todos.push(x)oruser.name = 'Ada'followed by a setter call. Build a new value instead. - Reading state right after setting it. The variable still holds the old value in the current render. Use the value you computed, or a functional update.
- Calling the setter during render. Writing
setCount(1)directly in the component body triggers a render, which calls it again, and React reports too many re-renders. Call setters from event handlers or effects. - Passing a call instead of a function.
onClick={setCount(count + 1)}runs during render. WriteonClick={() => setCount(count + 1)}. - Storing derived data. If a value can be computed from props or other state, such as
todos.length, compute it during render. A second state variable can fall out of sync. - Expecting state to be shared. State belongs to one component instance. To share it, move it to the nearest common parent and pass it down as props.
Exercises
Exercise
A component has const [count, setCount] = useState(0). A click handler runs setCount(count + 2) and then setCount(count + 3). What is count after the next render, and how would you make both updates apply?
Show answer
It is 3. Both calls use the same snapshot value 0, and the later update replaces the earlier one. Use functional updates, setCount(c => c + 2) and then setCount(c => c + 3), to get 5.
Exercise
This handler does not update the screen: const [user, setUser] = useState({ name: 'Ada', age: 36 }) and function birthday() { user.age = user.age + 1; setUser(user) }. Why, and what is the fix?
Show answer
The code mutates the existing object and passes the same reference, so Object.is finds no change and React may skip the render. Create a new object: setUser({ ...user, age: user.age + 1 }).
Exercise
Why does useState(loadBigList()) waste work, and what is the correct form?
Show answer
loadBigList() runs on every render, although React uses the result only on the first one. Pass a function so React calls it once: useState(() => loadBigList()), or useState(loadBigList).