Skip to content
Sarj Code Standards

react-prefer-updater-function

Use the updater form when the next React state is built from the current state.

Why

A state variable holds the snapshot from the render that created the callback. After an await, in a timer, promise callback, subscription or effect, or when two updates run before React re-renders, that snapshot is stale. setItems([...items, item]) then drops whatever another update added in the meantime. An updater receives the latest queued state, so each update builds on the one before it.

Fix

Pass an updater instead. Rewrite setItems([...items, item]) as setItems((previous) => [...previous, item]), and read previous wherever the argument read the state or a local derived from it. Compute IDs, timestamps and other impure values before the call, because React runs updaters twice in Strict Mode development builds.

Examples

Before — flagged Append to the render snapshot after an await
src/cart.tsx
import { useState } from "react";
export function Cart({ load }: { load: () => Promise<string> }) {
const [items, setItems] = useState<string[]>([]);
const add = async () => {
const item = await load();
setItems([...items, item]);
};
return (
<button type="button" onClick={add}>
{items.length}
</button>
);
}
After — preferred Append to the latest state through an updater
src/cart.tsx
import { useState } from "react";
export function Cart({ load }: { load: () => Promise<string> }) {
const [items, setItems] = useState<string[]>([]);
const add = async () => {
const item = await load();
setItems((previous) => [...previous, item]);
};
return (
<button type="button" onClick={add}>
{items.length}
</button>
);
}

References