ReactEasy

What is a functional update?

A functional update is updating state by passing a function to the setter, as in setItems((prev) => [...prev, item]), so the new state is computed from the most recent previous state rather than from a possibly stale variable captured in a closure.

Why it exists

State values inside a render are snapshots. If an update depends on the current value and the code runs later (after await, in a timer, in a subscription, or several times in a row), the captured value may be out of date. The functional form always receives the latest value React has.

Typical cases

  • setCount((c) => c + 1) in handlers that may fire quickly.
  • setTodos((ts) => ts.filter((t) => t.id !== id)) in callbacks passed to children.
  • setOpen((o) => !o) toggles.
  • Updates inside setInterval or WebSocket listeners registered once.
  • Async flows: after await, use the functional form to merge results into the latest state.

Not always necessary

If the new value does not depend on the old one (setName(e.target.value)), pass the value directly.

Class components

this.setState((prevState, props) => ({ count: prevState.count + props.step })).

Interview example

Explain why setCount(count + 1); setCount(count + 1); adds only 1, and fix it with the functional form.

Code example

tsx
1import { useState } from "react";
2
3type Message = { id: string; text: string };
4
5export function Chat() {
6 const [messages, setMessages] = useState<Message[]>([]);
7 const [count, setCount] = useState(0);
8
9 async function send(text: string) {
10 const optimistic = { id: crypto.randomUUID(), text };
11 setMessages((prev) => [...prev, optimistic]); // functional: safe even if more messages arrive
12
13 const saved: Message = await fetch("/api/messages", { method: "POST", body: JSON.stringify({ text }) }).then((r) => r.json());
14
15 // After await, `messages` from this render is stale; the functional form sees the latest list
16 setMessages((prev) => prev.map((m) => (m.id === optimistic.id ? saved : m)));
17 }
18
19 return (
20 <div>
21 <button onClick={() => send("Hello")}>Send</button>
22 <button onClick={() => { setCount(count + 1); setCount(count + 1); }}>Only +1: {count}</button>
23 <button onClick={() => { setCount((c) => c + 1); setCount((c) => c + 1); }}>Really +2</button>
24 <p>{messages.length} messages</p>
25 </div>
26 );
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app