Sub topic 3
Calculate values during render instead of syncing state
This chapter assumes you can write function components with JSX, use useState and props, and have seen useEffect with a dependency array. It also assumes you know that React re-renders a component when its state or props change.
The problem: state that mirrors other state
A common habit is to store every value a component shows in its own state variable, then use an Effect to keep those variables up to date. It feels natural because Effects "react to changes". In most cases it is unnecessary and makes the component slower and harder to follow.
Here is a form that shows a full name. It keeps fullName in state and updates it from an Effect:
import { useState, useEffect } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
// Avoid: redundant state and an unnecessary Effect
const [fullName, setFullName] = useState('');
useEffect(() => {
setFullName(firstName + ' ' + lastName);
}, [firstName, lastName]);
return (
<>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
<input value={lastName} onChange={e => setLastName(e.target.value)} />
<p>{fullName}</p>
</>
);
}This component works, but it does extra work. When you type a character:
setFirstNameruns and React renders with the newfirstNamebut the oldfullName.- React commits that result to the screen.
- The Effect runs and calls
setFullName. - React renders a second time and commits again.
For one render, the screen shows inconsistent data. The first name has changed, but the full name has not. Users rarely notice, but the component did two render passes where one was enough.
The fix: calculate during render
If a value can be computed from props or existing state, do not store it. Compute it in the component body:
import { useState } from 'react';
function Form() {
const [firstName, setFirstName] = useState('Taylor');
const [lastName, setLastName] = useState('Swift');
// Calculated during render. No extra state and no Effect.
const fullName = firstName + ' ' + lastName;
return (
<>
<input value={firstName} onChange={e => setFirstName(e.target.value)} />
<input value={lastName} onChange={e => setLastName(e.target.value)} />
<p>{fullName}</p>
</>
);
}Now fullName is always correct for the props and state of the current render. There is nothing to keep in sync, so it cannot drift out of sync.
Why this works
React calls your component function to produce a description of the UI. Each call is a snapshot. The values of firstName and lastName are fixed for that call, so any expression based on them is also fixed and correct for that snapshot.
An Effect, by contrast, runs after React has already rendered and committed. Anything you set from an Effect arrives one render late. This is why Effects are the wrong tool for values that only describe other values. They are for synchronizing with systems outside React, which this tutorial covers elsewhere.
Calculating during render is only safe if the calculation is pure. It should read props and state, return a result, and not change anything else. The previous chapter covers purity. In short, do not mutate variables defined outside the component or call APIs from the render body.
Common forms of redundant state
Redundant state appears in several shapes. Watch for these.
Filtering or transforming a list
// Avoid
const [todos, setTodos] = useState([]);
const [visibleTodos, setVisibleTodos] = useState([]);
useEffect(() => {
setVisibleTodos(todos.filter(t => !t.done));
}, [todos]);Replace it with a plain variable:
const [todos, setTodos] = useState([]);
const visibleTodos = todos.filter(t => !t.done);Counts, totals, and flags
Values such as todos.length, a cart total, or isEmpty are all derived. Compute them where you need them:
const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const isEmpty = items.length === 0;Storing a copy of a prop
// Avoid: the copy ignores later prop changes
function Price({ amount }) {
const [displayAmount, setDisplayAmount] = useState(amount);
useEffect(() => {
setDisplayAmount(amount);
}, [amount]);
return <span>${displayAmount.toFixed(2)}</span>;
}Use the prop directly:
function Price({ amount }) {
return <span>${amount.toFixed(2)}</span>;
}The exception is when you want the prop only as an initial value that the component then owns. In that case, name the prop to make the intent clear, for example initialAmount. Copying a prop into state only makes sense if later changes to the prop should be ignored.
Storing a selected object instead of its ID
A related case is selection. If you store a whole object in state, it can go stale when the list changes:
// Avoid: selectedItem is a copy that can go stale
const [items, setItems] = useState(initialItems);
const [selectedItem, setSelectedItem] = useState(items[0]);Store the ID and look up the object during render:
const [items, setItems] = useState(initialItems);
const [selectedId, setSelectedId] = useState(items[0].id);
const selectedItem = items.find(item => item.id === selectedId);When items changes, selectedItem reflects the new data automatically. If the selected item was removed, find returns undefined, so handle that case (for example, with selectedItem?.name) or reset selectedId in the handler that removes the item.
A decision table
| Situation | Better approach |
|---|---|
| Value computed from props or state | Plain variable in the render body |
| Computation is cheap | Plain variable, no memoization |
| Computation is measurably slow | `useMemo` (next chapter) |
| Need to reset all state when a prop changes | `key` (a later chapter) |
| Work caused by a user action | Event handler |
| Syncing with a network, DOM API, or widget | Effect |
Edge cases and gotchas
Calculation must be pure
A derived value should depend only on props and state. This breaks the rule:
let renderCount = 0;
function Counter({ value }) {
renderCount++; // Mutates a variable outside the component
const label = 'Render ' + renderCount + ': ' + value;
return <p>{label}</p>;
}The result changes between renders even with the same props, and React may call a component function more than once (for example, Strict Mode in development does this on purpose to surface such bugs).
Do not call `setState` unconditionally during render
You might be tempted to "derive" state by calling a setter in the body. This creates an update loop unless guarded, and it is a special case reserved for adjusting state when a prop changes. For ordinary derived values, a variable is simpler and correct.
Mutating state while deriving
Methods such as sort and reverse change the array they are called on. Never call them directly on a state array:
// Avoid: sort mutates the state array
const sorted = todos.sort((a, b) => a.text.localeCompare(b.text));
// Correct: copy first
const sortedTodos = [...todos].sort((a, b) => a.text.localeCompare(b.text));In modern runtimes you can also use todos.toSorted(...), which returns a new array.
Derived values that feel expensive
Many developers reach for state or an Effect because a calculation "might be slow". Usually it is not. Filtering a list of a few hundred items takes microseconds. Measure first. If a calculation really is slow, caching it is a separate step from storing it in state, and it uses useMemo, covered in the next chapter.
Values that really must be state
Some values look derived but are not. If a value depends on something that happened (a click count, a draft the user typed, a response from a server), it is information the component cannot recompute from props alone. That is genuine state. The question to ask is whether the value can be recomputed from current props and state at any time. If yes, derive it. If no, it is state.
A worked refactor
Consider a shopping cart summary that stores three values in state and syncs them with Effects:
import { useState, useEffect } from 'react';
function CartSummary({ items }) {
const [total, setTotal] = useState(0);
const [count, setCount] = useState(0);
const [hasItems, setHasItems] = useState(false);
useEffect(() => {
setTotal(items.reduce((sum, i) => sum + i.price * i.quantity, 0));
setCount(items.reduce((sum, i) => sum + i.quantity, 0));
setHasItems(items.length > 0);
}, [items]);
if (!hasItems) return <p>Your cart is empty.</p>;
return <p>{count} items, ${total.toFixed(2)}</p>;
}On the first render, hasItems is false, so the user briefly sees "Your cart is empty" even when the cart has items. Every change to items causes a second render.
The derived version has no state at all:
function CartSummary({ items }) {
const total = items.reduce((sum, i) => sum + i.price * i.quantity, 0);
const count = items.reduce((sum, i) => sum + i.quantity, 0);
if (items.length === 0) return <p>Your cart is empty.</p>;
return <p>{count} items, ${total.toFixed(2)}</p>;
}It is shorter, renders once per change, and has no flash of incorrect content.
How to spot the pattern in your own code
Look for an Effect with these traits:
- The body only calls state setters.
- The dependency array lists values that are props or other state from the same component.
- It does not talk to anything outside React.
Each of these is a strong sign the state being set is derived. Delete the state variable, replace it with a calculation, and remove the Effect.
Exercise
A component has const [items, setItems] = useState([]), const [query, setQuery] = useState(''), and const [matches, setMatches] = useState([]). An Effect with dependencies [items, query] calls setMatches(items.filter(i => i.name.includes(query))). How would you rewrite it, and why does the rewrite remove a wasted render?
Show answer
Delete the matches state and the Effect, and compute const matches = items.filter(i => i.name.includes(query)); in the component body. With the Effect, each change to items or query first renders with a stale matches, commits, then runs the Effect, which sets state and triggers a second render. The calculated version produces the correct matches in the same render that sees the new items or query, so there is only one render pass and no stale intermediate output.
Exercise
A list component stores const [selectedUser, setSelectedUser] = useState(users[0]). After the users array is refreshed from the server, the details panel still shows old data for the selected user. What is the cause, and what is the fix?
Show answer
selectedUser is a copy of an object from an earlier users array, so it does not update when users changes. Store only the ID with const [selectedId, setSelectedId] = useState(users[0].id) and derive the object during render with const selectedUser = users.find(u => u.id === selectedId);. The lookup then always uses the current data. Handle the case where find returns undefined if the user can disappear from the list.