Stop using useEffect for derived state: compute it during render
Guide/ 11 min read
If a value comes from props or state, do not copy it with useEffect: compute it during render. Measured in Chromium with React 19: one render fewer and no stale values.
- React
- JavaScript
In this article (7)
Do not use useEffect for derived state. If a value can be calculated from props or state, like a cart total or a filtered list, compute it during render. With an Effect, React renders with the stale value, runs the Effect and renders again: one extra render and a moment of out-of-sync data on screen.
This article measures five common store components with React 19 in Chromium, counting real renders, and shows when useMemo is worth adding. If you work with Next.js, also check where to put use client: Effects and useMemo only work in Client Components.
The double render of useEffect and out-of-sync state
This is the pattern to remove. The cart total lives in state, and an Effect recalculates it whenever the items change:
export function CartTotalBefore({ items }) {
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price * item.qty, 0));
}, [items]);
return <p>{items.length} items · total {(total / 100).toFixed(2)}</p>;
}
useState(0)creates a second source of truth: the total can already be derived fromitems, but now it also lives on its own.- The Effect runs after React has committed the component to the DOM, and only then calculates the total.
setTotalschedules another render. Until it happens, the screen shows the new items with the old total.- Amounts are in cents;
toFixed(2)prints them with two decimals.
React's own guide, You Might Not Need an Effect, explains why this is inefficient: when state changes, React calls your components, commits the result to the DOM and then runs your Effects. If an Effect immediately updates state, the whole process restarts from scratch.
We measured it. We bundled this article's examples with esbuild and the project's React 19.0 and react-dom, and ran them in Chromium 151 with Playwright. A counter recorded every call to the component, and a React <Profiler> saved the DOM text after each commit. Clicking to add a third 2.50 item to a 12.50 cart:
Scroll the figure sideways to see all of it
- With the Effect: 2 renders and 2 commits. The first commit put "3 items · total 12.50" in the DOM, a total that did not match the items. The second fixed it to 15.00.
- Computed during render: 1 render and 1 commit, showing "3 items · total 15.00" from the start.
Does the stale value ever reach the screen? It depends. Per the useEffect reference, when an Effect was not caused by an interaction, React usually lets the browser paint before running it, so on mount the "total 0.00" can be painted. When a click caused it, React may run the Effect before paint. The extra render happens either way, and any code that reads the total during that first render, such as a free-shipping banner, works with the wrong number.
Do not confuse it with StrictMode's double render
Our numbers are without StrictMode. In development, StrictMode calls every component twice to catch impure rendering and runs every Effect one extra time, in development only; the production build is unaffected. With StrictMode on we counted 4 calls with the Effect and 2 without it, while commits stayed at 2 and 1. The production build, without StrictMode, gave the same numbers as development: 2 renders with the Effect and 1 without. The Effect's extra render is real, in production too. If you use the Next.js App Router, StrictMode has been on by default since 13.5.1, per the reactStrictMode docs.
Calculate it during render
The rule in React's docs is plain: when something can be calculated from the existing props or state, do not put it in state; calculate it during rendering. The same component becomes:
export function CartTotal({ items }) {
const total = items.reduce((sum, item) => sum + item.price * item.qty, 0);
return <p>{items.length} items · total {(total / 100).toFixed(2)}</p>;
}
- No
useState, nouseEffect:totalis a constant recomputed on every render. - Because it comes from
itemsin the same render, it cannot go stale. - The JSX is unchanged, which is why both versions ended with identical text in our test.
Scroll the figure sideways to see all of it
Per the guide, this makes the code faster (no cascading updates), simpler (less code) and less error-prone (no two pieces of state drifting apart). Two variations of the same idea are worth knowing: to reset all of a component's state when a prop changes, give it a different key; and instead of storing the selected object, store its id and look it up during render.
When useMemo is worth it
Recomputing on every render is fine most of the time. The docs suggest timing the calculation with console.time and considering useMemo once it adds up to 1 ms or more; in general, unless you create or loop over thousands of objects, it is probably not expensive. This catalog has a search box, and every keystroke re-renders the component:
export function Catalog({ products }) {
const [query, setQuery] = useState("");
const sorted = useMemo(() => products.toSorted((a, b) => a.price - b.price), [products]);
const visible = sorted.filter((p) => p.name.includes(query)).slice(0, 20);
return (
<>
<input aria-label="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
<ol>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ol>
</>
);
}
queryis the search text: it changes on every keystroke.useMemokeeps the sorted result and only recomputes it whenproductschanges. React compares each dependency withObject.is.toSortedreturns a new array;sort()would sort the array that came in through props in place.- The text filter does run on every keystroke, because it depends on
query. slice(0, 20)caps what gets rendered at 20 products.
We measured it with 20,000 products (an illustrative size), a production build and three keystrokes, as the guide recommends: in production, and again with Chromium's CPU throttled 4×. To count without touching the component, the test page wrapped Array.prototype.toSorted. These are local lab measurements from two runs:
| Catalog of 20,000 products | Sorts while typing 3 letters | Time per sort |
|---|---|---|
Without useMemo | 3 | 3–5 ms; 14–25 ms with a 4× slower CPU |
With useMemo | 0 | No sorting while typing |
| Mount, both versions | 1 | The same: useMemo does not speed up the first render |
That is the case the useMemo reference calls valuable: a noticeably slow calculation whose dependencies rarely change. It also helps when you pass the value to a component wrapped in memo, or when it is a dependency of another Hook. Outside those cases it adds nothing, and the reference is firm on one more point: rely on useMemo only as a performance optimization. If your code breaks without it, the bug is somewhere else.
5 before-and-after examples: cart total, filters, full name, sorting, counts
All five are real components we ran side by side. In every case the Effect version took 2 renders on mount and 2 on update, and the version computed during render took 1 and 1, ending with the same text:
| Example | With useEffect (mount / update) | During render | What the in-between commit showed |
|---|---|---|---|
| Cart total | 2 / 2 renders | 1 / 1 | "3 items · total 12.50" instead of 15.00 |
| Filters | 2 / 2 renders | 1 / 1 | An empty list on mount; the previous category on change |
| Full name | 2 / 2 renders | 1 / 1 | "Ana López" with "Beatriz" already typed in the field |
| Sorting | 2 / 2 renders | 1 / 1 | An empty list on mount; the old order on change |
| Counts | 2 / 2 renders | 1 / 1 | "0 pending · 0 shipped" on mount |
1. Cart total
The example from the sections above, with both versions together exactly as we ran them:
// 1. Cart total — before
export function CartTotalBefore({ items }) {
const [total, setTotal] = useState(0);
useEffect(() => {
setTotal(items.reduce((sum, item) => sum + item.price * item.qty, 0));
}, [items]);
return <p>{items.length} items · total {(total / 100).toFixed(2)}</p>;
}
// 1. Cart total — after
export function CartTotal({ items }) {
const total = items.reduce((sum, item) => sum + item.price * item.qty, 0);
return <p>{items.length} items · total {(total / 100).toFixed(2)}</p>;
}
- Before: a piece of state and an Effect for something one line can calculate.
- After:
reduceadds up price times quantity in the same render.
2. Filters
// 2. Filters — before
export function ProductListBefore({ products, category }) {
const [visible, setVisible] = useState([]);
useEffect(() => {
setVisible(products.filter((p) => p.category === category && p.stock > 0));
}, [products, category]);
return <ul>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
// 2. Filters — after
export function ProductList({ products, category }) {
const visible = products.filter((p) => p.category === category && p.stock > 0);
return <ul>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
- Before:
visiblestarts empty, so the first commit paints a list with no products. - After:
filterruns during render with the current category and keeps only in-stock products.
3. Full name
// 3. Full name — before
const [firstName, setFirstName] = useState("Ana");
const [lastName, setLastName] = useState("López");
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
// 3. Full name — after
const [firstName, setFirstName] = useState("Ana");
const [lastName, setLastName] = useState("López");
const fullName = firstName + " " + lastName;
- Before: this is the example from React's docs.
fullNameis redundant state, and while typing, the first render shows the previous name. - After: one concatenation. The JSX with the two inputs is the same in both versions.
4. Sorting
// 4. Sorting — before
export function SortedProductsBefore({ products, sortBy }) {
const [sorted, setSorted] = useState([]);
useEffect(() => {
setSorted(products.toSorted((a, b) => a[sortBy] - b[sortBy]));
}, [products, sortBy]);
return <ol>{sorted.map((p) => <li key={p.id}>{p.name}</li>)}</ol>;
}
// 4. Sorting — after
export function SortedProducts({ products, sortBy }) {
const sorted = products.toSorted((a, b) => a[sortBy] - b[sortBy]);
return <ol>{sorted.map((p) => <li key={p.id}>{p.name}</li>)}</ol>;
}
- Before: when
sortBychanges, the first commit still shows the old order. - After: toSorted builds a new array on every render. For long lists, wrap it in
useMemoas in the catalog.
5. Counts
// 5. Counts — before
export function OrderCountsBefore({ orders }) {
const [pending, setPending] = useState(0);
const [shipped, setShipped] = useState(0);
useEffect(() => {
setPending(orders.filter((o) => o.status === "pending").length);
setShipped(orders.filter((o) => o.status === "shipped").length);
}, [orders]);
return <p>{pending} pending · {shipped} shipped</p>;
}
// 5. Counts — after
export function OrderCounts({ orders }) {
const pending = orders.filter((o) => o.status === "pending").length;
const shipped = orders.filter((o) => o.status === "shipped").length;
return <p>{pending} pending · {shipped} shipped</p>;
}
- Before: two pieces of state and two setters in one Effect. React batches them into a single extra render, but they are still two copies to keep in sync.
- After: two
filter(...).lengthcalls. If there are thousands of orders and the component renders often, measure before memoizing.
Scroll the figure sideways to see all of it
Common mistakes
- Copying props into state "to have them handy". Every copy is one more value that can go stale. If it comes from props, compute it.
- Sorting props with
sort().sort()mutates the original array. UsetoSorted()or copy first. - Wrapping everything in
useMemojust in case. Per its reference, outside slow calculations,memochildren or Hook dependencies it adds nothing and makes the code harder to read. - Using
useMemoto fix a bug. It is only an optimization, and React may throw the cached value away. If the code fails without it, fix the cause. - Measuring performance in development. StrictMode doubles the calls. The guide recommends a production build on a device like your users'.
- Chaining Effects. An Effect that sets state that triggers another Effect multiplies renders. If a user action is the cause, do all of it in the event handler.
- Resetting state with an Effect when a prop changes. Pass a different
keyand React resets the component without the extra render.
Frequently asked questions
Why does my component render twice in development?
Almost always because of StrictMode: in development it calls every component twice and runs every Effect one extra time, and none of that happens in production. The extra render from an Effect that sets state is a different problem, and that one does happen in production, as we measured.
So when should I use useEffect?
To synchronize with something outside React: a network connection, a browser API or a non-React widget. If code should run because the user did something, it belongs in the event handler. You can also fetch data in an Effect, but you need cleanup to avoid race conditions.
Does the React Compiler make useMemo unnecessary?
The useMemo reference says the compiler memoizes values and functions automatically, reducing the need for manual calls. Even so, a derived value should not live in separate state: that is not a memoization problem.
Isn't recomputing on every render slower?
For sums, filters and counts over tens or hundreds of items, you will not notice. In our test, sorting 20,000 products took 3 to 5 ms: that is where useMemo pays off. Time it with console.time before you decide.
Checklist
- No state holds something that can be calculated from props or other state.
- No Effect exists only to call a setter with derived data.
useMemoonly wraps calculations you measured at 1 ms or more, in production.- Sorting uses
toSorted()or a copy, neversort()on props. - Whatever the user causes runs in the event handler, not in an Effect.
- To reset a component when a prop changes, you pass a
key. - The Effects that remain sync with something external and clean up after themselves.
Computing during render leaves less code, one render fewer and no stale values. If your project is Next.js, continue with where to put use client so these components only ship JavaScript where they need to, and if your add-to-cart button feels slow, read how to measure and fix its INP.
Saw this on Instagram? Comment EFFECT on the Reel and I'll send you the guide.
Written by

Published October 30, 2026 · updated November 1, 2026